home *** CD-ROM | disk | FTP | other *** search
/ Turnbull China Bikeride / Turnbull China Bikeride - Disc 2.iso / BARNET / BZIP2 / 980205 / bzip / c / bzip2 next >
Text File  |  1998-02-05  |  119KB  |  4,141 lines

  1. /*-----------------------------------------------------------*/
  2. /*--- A block-sorting, lossless compressor        bzip2.c ---*/
  3. /*-----------------------------------------------------------*/
  4.  
  5. /*--
  6.   This program is bzip2, a lossless, block-sorting data compressor,
  7.   version 0.1pl2, dated 29-Aug-1997.
  8.  
  9.   Copyright (C) 1996, 1997 by Julian Seward.
  10.      Guildford, Surrey, UK
  11.      email: jseward@acm.org
  12.  
  13.   This program is free software; you can redistribute it and/or modify
  14.   it under the terms of the GNU General Public License as published by
  15.   the Free Software Foundation; either version 2 of the License, or
  16.   (at your option) any later version.
  17.  
  18.   This program is distributed in the hope that it will be useful,
  19.   but WITHOUT ANY WARRANTY; without even the implied warranty of
  20.   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  21.   GNU General Public License for more details.
  22.  
  23.   You should have received a copy of the GNU General Public License
  24.   along with this program; if not, write to the Free Software
  25.   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  26.  
  27.   The GNU General Public License is contained in the file LICENSE.
  28.  
  29.   This program is based on (at least) the work of:
  30.      Mike Burrows
  31.      David Wheeler
  32.      Peter Fenwick
  33.      Alistair Moffat
  34.      Radford Neal
  35.      Ian H. Witten
  36.      Robert Sedgewick
  37.      Jon L. Bentley
  38.  
  39.   For more information on these sources, see the file ALGORITHMS.
  40. --*/
  41.  
  42. /*----------------------------------------------------*/
  43. /*--- IMPORTANT                                    ---*/
  44. /*----------------------------------------------------*/
  45.  
  46. /*--
  47.    WARNING:
  48.       This program (attempts to) compress data by performing several
  49.       non-trivial transformations on it.  Unless you are 100% familiar
  50.       with *all* the algorithms contained herein, and with the
  51.       consequences of modifying them, you should NOT meddle with the
  52.       compression or decompression machinery.  Incorrect changes can
  53.       and very likely *will* lead to disasterous loss of data.
  54.  
  55.    DISCLAIMER:
  56.       I TAKE NO RESPONSIBILITY FOR ANY LOSS OF DATA ARISING FROM THE
  57.       USE OF THIS PROGRAM, HOWSOEVER CAUSED.
  58.  
  59.       Every compression of a file implies an assumption that the
  60.       compressed file can be decompressed to reproduce the original.
  61.       Great efforts in design, coding and testing have been made to
  62.       ensure that this program works correctly.  However, the
  63.       complexity of the algorithms, and, in particular, the presence
  64.       of various special cases in the code which occur with very low
  65.       but non-zero probability make it impossible to rule out the
  66.       possibility of bugs remaining in the program.  DO NOT COMPRESS
  67.       ANY DATA WITH THIS PROGRAM UNLESS YOU ARE PREPARED TO ACCEPT THE
  68.       POSSIBILITY, HOWEVER SMALL, THAT THE DATA WILL NOT BE RECOVERABLE.
  69.  
  70.       That is not to say this program is inherently unreliable.
  71.       Indeed, I very much hope the opposite is true.  bzip2 has been
  72.       carefully constructed and extensively tested.
  73.  
  74.    PATENTS:
  75.       To the best of my knowledge, bzip2 does not use any patented
  76.       algorithms.  However, I do not have the resources available to
  77.       carry out a full patent search.  Therefore I cannot give any
  78.       guarantee of the above statement.
  79. --*/
  80.  
  81.  
  82.  
  83. /*----------------------------------------------------*/
  84. /*--- and now for something much more pleasant :-) ---*/
  85. /*----------------------------------------------------*/
  86.  
  87. /*---------------------------------------------*/
  88. /*--
  89.   Place a 1 beside your platform, and 0 elsewhere.
  90. --*/
  91.  
  92. /*--
  93.   Generic 32-bit Unix.
  94.   Also works on 64-bit Unix boxes.
  95. --*/
  96. #define BZ_UNIX        0
  97.  
  98. /*--
  99.   Win32, as seen by Jacob Navia's excellent
  100.   port of (Chris Fraser & David Hanson)'s excellent
  101.   lcc compiler.
  102. --*/
  103. #define BZ_LCCWIN32    0
  104.  
  105. /*--
  106.   Acorn's RISC OS (currently requires unixlib & gcc)
  107. --*/
  108.  
  109. #define BZ_RISCOS    1
  110.  
  111. /*---------------------------------------------*/
  112. /*--
  113.   Some stuff for all platforms.
  114. --*/
  115.  
  116. #include <stdio.h>
  117. #include <stdlib.h>
  118. #if DEBUG
  119.   #include <assert.h>
  120. #endif
  121. #include <string.h>
  122. #include <signal.h>
  123. #include <math.h>
  124.  
  125. #define ERROR_IF_EOF(i)       { if ((i) == EOF)  ioError(); }
  126. #define ERROR_IF_NOT_ZERO(i)  { if ((i) != 0)    ioError(); }
  127. #define ERROR_IF_MINUS_ONE(i) { if ((i) == (-1)) ioError(); }
  128.  
  129.  
  130. /*---------------------------------------------*/
  131. /*--
  132.    Platform-specific stuff.
  133. --*/
  134.  
  135. #if BZ_UNIX
  136.    #include <sys/types.h>
  137.    #include <utime.h>
  138.    #include <unistd.h>
  139.    #include <malloc.h>
  140.    #include <sys/stat.h>
  141.    #include <sys/times.h>
  142.  
  143.    #define Int32   int
  144.    #define UInt32  unsigned int
  145.    #define Char    char
  146.    #define UChar   unsigned char
  147.    #define Int16   short
  148.    #define UInt16  unsigned short
  149.  
  150.    #define PATH_SEP    '/'
  151.    #define MY_LSTAT    lstat
  152.    #define MY_S_IFREG  S_ISREG
  153.    #define MY_STAT     stat
  154.  
  155.    #define APPEND_FILESPEC(root, name) \
  156.       root=snocString((root), (name))
  157.  
  158.    #define SET_BINARY_MODE(fd) /**/
  159.  
  160.    /*--
  161.       You should try very hard to persuade your C compiler
  162.       to inline the bits marked INLINE.  Otherwise bzip2 will
  163.       run rather slowly.  gcc version 2.x is recommended.
  164.    --*/
  165.    #ifdef __GNUC__
  166.       #define INLINE   inline
  167.       #define NORETURN __attribute__ ((noreturn))
  168.    #else
  169.       #define INLINE   /**/
  170.       #define NORETURN /**/
  171.    #endif
  172. #endif
  173.  
  174.  
  175.  
  176. #if BZ_LCCWIN32
  177.    #include <io.h>
  178.    #include <fcntl.h>
  179.    #include <sys\stat.h>
  180.  
  181.    #define Int32   int
  182.    #define UInt32  unsigned int
  183.    #define Int16   short
  184.    #define UInt16  unsigned short
  185.    #define Char    char
  186.    #define UChar   unsigned char
  187.  
  188.    #define INLINE         /**/
  189.    #define NORETURN       /**/
  190.    #define PATH_SEP       '\\'
  191.    #define MY_LSTAT       _stat
  192.    #define MY_STAT        _stat
  193.    #define MY_S_IFREG(x)  ((x) & _S_IFREG)
  194.  
  195.    #if 0
  196.    /*-- lcc-win32 seems to expand wildcards itself --*/
  197.    #define APPEND_FILESPEC(root, spec)                \
  198.       do {                                            \
  199.          if ((spec)[0] == '-') {                      \
  200.             root = snocString((root), (spec));        \
  201.          } else {                                     \
  202.             struct _finddata_t c_file;                \
  203.             long hFile;                               \
  204.             hFile = _findfirst((spec), &c_file);      \
  205.             if ( hFile == -1L ) {                     \
  206.                root = snocString ((root), (spec));    \
  207.             } else {                                  \
  208.                int anInt = 0;                         \
  209.                while ( anInt == 0 ) {                 \
  210.                   root = snocString((root),           \
  211.                             &c_file.name[0]);         \
  212.                   anInt = _findnext(hFile, &c_file);  \
  213.                }                                      \
  214.             }                                         \
  215.          }                                            \
  216.       } while ( 0 )
  217.    #else
  218.    #define APPEND_FILESPEC(root, name)                \
  219.       root = snocString ((root), (name))
  220.    #endif
  221.  
  222.    #define SET_BINARY_MODE(fd)                        \
  223.       do {                                            \
  224.          int retVal = setmode ( fileno ( fd ),        \
  225.                                O_BINARY );            \
  226.          ERROR_IF_MINUS_ONE ( retVal );               \
  227.       } while ( 0 )
  228.  
  229. #endif
  230.  
  231. #if BZ_RISCOS
  232.    #define BZ_FILETYPE 0x16E
  233.  
  234.    #include <sys/types.h>
  235.    #include <stdio.h>        /* required by tmpnam() */
  236.    #include <sys/os.h>        /* required by os_file() */
  237.    #include <utime.h>
  238.    #include <unistd.h>        /* can i narrow this down & remove it? */
  239.    #include <malloc.h>
  240.    #include <sys/stat.h>
  241.    #include <sys/times.h>
  242.  
  243.    #define Int32   int
  244.    #define UInt32  unsigned int
  245.    #define Char    char
  246.    #define UChar   unsigned char
  247.    #define Int16   short
  248.    #define UInt16  unsigned short
  249.  
  250.    #define PATH_SEP    '.'
  251.    #define MY_LSTAT    lstat
  252.    #define MY_S_IFREG  S_ISREG
  253.    #define MY_STAT     stat
  254.  
  255.    #define APPEND_FILESPEC(root, name) \
  256.       root=snocString((root), (name))
  257.  
  258.    #define SET_BINARY_MODE(fd) /**/
  259.  
  260.    /*--
  261.       You should try very hard to persuade your C compiler
  262.       to inline the bits marked INLINE.  Otherwise bzip2 will
  263.       run rather slowly.  gcc version 2.x is recommended.
  264.    --*/
  265.    #ifdef __GNUC__
  266.       #define INLINE   inline
  267.       #define NORETURN __attribute__ ((noreturn))
  268.    #else
  269.       #define INLINE   /**/
  270.       #define NORETURN /**/
  271.    #endif
  272. #endif
  273.  
  274. /*---------------------------------------------*/
  275. /*--
  276.   Some more stuff for all platforms :-)
  277. --*/
  278.  
  279. #define Bool   unsigned char
  280. #define True   1
  281. #define False  0
  282.  
  283. /*--
  284.   IntNative is your platform's `native' int size.
  285.   Only here to avoid probs with 64-bit platforms.
  286. --*/
  287. #define IntNative int
  288.  
  289.  
  290. /*--
  291.    change to 1, or compile with -DDEBUG=1 to debug
  292. --*/
  293. #ifndef DEBUG
  294. #define DEBUG 0
  295. #endif
  296.  
  297.  
  298. /*---------------------------------------------------*/
  299. /*---                                             ---*/
  300. /*---------------------------------------------------*/
  301.  
  302. /*--
  303.    Implementation notes, July 1997
  304.    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  305.  
  306.    Memory allocation
  307.    ~~~~~~~~~~~~~~~~~
  308.    All large data structures are allocated on the C heap,
  309.    for better or for worse.  That includes the various
  310.    arrays of pointers, striped words, bytes, frequency
  311.    tables and buffers for compression and decompression.
  312.  
  313.    bzip2 can operate at various block-sizes, ranging from
  314.    100k to 900k in 100k steps, and it allocates only as
  315.    much as it needs to.  When compressing, we know from the
  316.    command-line options what the block-size is going to be,
  317.    so all allocation can be done at start-up; if that
  318.    succeeds, there can be no further allocation problems.
  319.  
  320.    Decompression is more complicated.  Each compressed file
  321.    contains, in its header, a byte indicating the block
  322.    size used for compression.  This means bzip2 potentially
  323.    needs to reallocate memory for each file it deals with,
  324.    which in turn opens the possibility for a memory allocation
  325.    failure part way through a run of files, by encountering
  326.    a file requiring a much larger block size than all the
  327.    ones preceding it.
  328.  
  329.    The policy is to simply give up if a memory allocation
  330.    failure occurs.  During decompression, it would be
  331.    possible to move on to subsequent files in the hope that
  332.    some might ask for a smaller block size, but the
  333.    complications for doing this seem more trouble than they
  334.    are worth.
  335.  
  336.  
  337.    Compressed file formats
  338.    ~~~~~~~~~~~~~~~~~~~~~~~
  339.    [This is now entirely different from both 0.21, and from
  340.     any previous Huffman-coded variant of bzip.
  341.     See the associated file bzip2.txt for details.]
  342.  
  343.  
  344.    Error conditions
  345.    ~~~~~~~~~~~~~~~~
  346.    Dealing with error conditions is the least satisfactory
  347.    aspect of bzip2.  The policy is to try and leave the
  348.    filesystem in a consistent state, then quit, even if it
  349.    means not processing some of the files mentioned in the
  350.    command line.  `A consistent state' means that a file
  351.    exists either in its compressed or uncompressed form,
  352.    but not both.  This boils down to the rule `delete the
  353.    output file if an error condition occurs, leaving the
  354.    input intact'.  Input files are only deleted when we can
  355.    be pretty sure the output file has been written and
  356.    closed successfully.
  357.  
  358.    Errors are a dog because there's so many things to
  359.    deal with.  The following can happen mid-file, and
  360.    require cleaning up.
  361.  
  362.      internal `panics' -- indicating a bug
  363.      corrupted or inconsistent compressed file
  364.      can't allocate enough memory to decompress this file
  365.      I/O error reading/writing/opening/closing
  366.      signal catches -- Control-C, SIGTERM, SIGHUP.
  367.  
  368.    Other conditions, primarily pertaining to file names,
  369.    can be checked in-between files, which makes dealing
  370.    with them easier.
  371. --*/
  372.  
  373.  
  374.  
  375. /*---------------------------------------------------*/
  376. /*--- Misc (file handling) data decls             ---*/
  377. /*---------------------------------------------------*/
  378.  
  379. UInt32  bytesIn, bytesOut;
  380. Int32   verbosity;
  381. Bool    keepInputFiles, smallMode, testFailsExist;
  382. UInt32  globalCrc;
  383. Int32   numFileNames, numFilesProcessed;
  384.  
  385.  
  386. /*-- source modes; F==file, I==stdin, O==stdout --*/
  387. #define SM_I2O           1
  388. #define SM_F2O           2
  389. #define SM_F2F           3
  390.  
  391. /*-- operation modes --*/
  392. #define OM_Z             1
  393. #define OM_UNZ           2
  394. #define OM_TEST          3
  395.  
  396. Int32   opMode;
  397. Int32   srcMode;
  398.  
  399.  
  400. Int32   longestFileName;
  401. Char    inName[1024];
  402. Char    outName[1024];
  403. Char    *progName;
  404. Char    progNameReally[1024];
  405. FILE    *outputHandleJustInCase;
  406.  
  407. void    panic                 ( Char* )          NORETURN;
  408. void    ioError               ( void )           NORETURN;
  409. void    compressOutOfMemory   ( Int32, Int32 )   NORETURN;
  410. void    uncompressOutOfMemory ( Int32, Int32 )   NORETURN;
  411. void    blockOverrun          ( void )           NORETURN;
  412. void    badBlockHeader        ( void )           NORETURN;
  413. void    badBGLengths          ( void )           NORETURN;
  414. void    crcError              ( UInt32, UInt32 ) NORETURN;
  415. void    bitStreamEOF          ( void )           NORETURN;
  416. void    cleanUpAndFail        ( Int32 )          NORETURN;
  417. void    compressedStreamEOF   ( void )           NORETURN;
  418.  
  419. void*   myMalloc ( Int32 );
  420.  
  421.  
  422.  
  423. /*---------------------------------------------------*/
  424. /*--- Data decls for the front end                ---*/
  425. /*---------------------------------------------------*/
  426.  
  427. /*--
  428.    The overshoot bytes allow us to avoid most of
  429.    the cost of pointer renormalisation during
  430.    comparison of rotations in sorting.
  431.    The figure of 20 is derived as follows:
  432.       qSort3 allows an overshoot of up to 10.
  433.       It then calls simpleSort, which calls
  434.       fullGtU, also with max overshoot 10.
  435.       fullGtU does up to 10 comparisons without
  436.       renormalising, giving 10+10 == 20.
  437. --*/
  438. #define NUM_OVERSHOOT_BYTES 20
  439.  
  440. /*--
  441.   These are the main data structures for
  442.   the Burrows-Wheeler transform.
  443. --*/
  444.  
  445. /*--
  446.   Pointers to compression and decompression
  447.   structures.  Set by
  448.      allocateCompressStructures   and
  449.      setDecompressStructureSizes
  450.  
  451.   The structures are always set to be suitable
  452.   for a block of size 100000 * blockSize100k.
  453. --*/
  454. UChar    *block;    /*-- compress   --*/
  455. UInt16   *quadrant; /*-- compress   --*/
  456. Int32    *zptr;     /*-- compress   --*/
  457. UInt16   *szptr;    /*-- overlays zptr ---*/
  458. Int32    *ftab;     /*-- compress   --*/
  459.  
  460. UInt16   *ll16;     /*-- small decompress --*/
  461. UChar    *ll4;      /*-- small decompress --*/
  462.  
  463. Int32    *tt;       /*-- fast decompress  --*/
  464. UChar    *ll8;      /*-- fast decompress  --*/
  465.  
  466.  
  467. /*--
  468.   freq table collected to save a pass over the data
  469.   during decompression.
  470. --*/
  471. Int32   unzftab[256];
  472.  
  473.  
  474. /*--
  475.    index of the last char in the block, so
  476.    the block size == last + 1.
  477. --*/
  478. Int32  last;
  479.  
  480.  
  481. /*--
  482.   index in zptr[] of original string after sorting.
  483. --*/
  484. Int32  origPtr;
  485.  
  486.  
  487. /*--
  488.   always: in the range 0 .. 9.
  489.   The current block size is 100000 * this number.
  490. --*/
  491. Int32  blockSize100k;
  492.  
  493.  
  494. /*--
  495.   Used when sorting.  If too many long comparisons
  496.   happen, we stop sorting, randomise the block
  497.   slightly, and try again.
  498. --*/
  499.  
  500. Int32  workFactor;
  501. Int32  workDone;
  502. Int32  workLimit;
  503. Bool   blockRandomised;
  504. Bool   firstAttempt;
  505. Int32  nBlocksRandomised;
  506.  
  507.  
  508.  
  509. /*---------------------------------------------------*/
  510. /*--- Data decls for the back end                 ---*/
  511. /*---------------------------------------------------*/
  512.  
  513. #define MAX_ALPHA_SIZE 258
  514. #define MAX_CODE_LEN    23
  515.  
  516. #define RUNA 0
  517. #define RUNB 1
  518.  
  519. #define N_GROUPS 6
  520. #define G_SIZE   50
  521. #define N_ITERS  4
  522.  
  523. #define MAX_SELECTORS (2 + (900000 / G_SIZE))
  524.  
  525. Bool  inUse[256];
  526. Int32 nInUse;
  527.  
  528. UChar seqToUnseq[256];
  529. UChar unseqToSeq[256];
  530.  
  531. UChar selector   [MAX_SELECTORS];
  532. UChar selectorMtf[MAX_SELECTORS];
  533.  
  534. Int32 nMTF;
  535.  
  536. Int32 mtfFreq[MAX_ALPHA_SIZE];
  537.  
  538. UChar len  [N_GROUPS][MAX_ALPHA_SIZE];
  539.  
  540. /*-- decompress only --*/
  541. Int32 limit  [N_GROUPS][MAX_ALPHA_SIZE];
  542. Int32 base   [N_GROUPS][MAX_ALPHA_SIZE];
  543. Int32 perm   [N_GROUPS][MAX_ALPHA_SIZE];
  544. Int32 minLens[N_GROUPS];
  545.  
  546. /*-- compress only --*/
  547. Int32  code [N_GROUPS][MAX_ALPHA_SIZE];
  548. Int32  rfreq[N_GROUPS][MAX_ALPHA_SIZE];
  549.  
  550.  
  551. /*---------------------------------------------------*/
  552. /*--- 32-bit CRC grunge                           ---*/
  553. /*---------------------------------------------------*/
  554.  
  555. /*--
  556.   I think this is an implementation of the AUTODIN-II,
  557.   Ethernet & FDDI 32-bit CRC standard.  Vaguely derived
  558.   from code by Rob Warnock, in Section 51 of the
  559.   comp.compression FAQ.
  560. --*/
  561.  
  562. UInt32 crc32Table[256] = {
  563.  
  564.    /*-- Ugly, innit? --*/
  565.  
  566.    0x00000000UL, 0x04c11db7UL, 0x09823b6eUL, 0x0d4326d9UL,
  567.    0x130476dcUL, 0x17c56b6bUL, 0x1a864db2UL, 0x1e475005UL,
  568.    0x2608edb8UL, 0x22c9f00fUL, 0x2f8ad6d6UL, 0x2b4bcb61UL,
  569.    0x350c9b64UL, 0x31cd86d3UL, 0x3c8ea00aUL, 0x384fbdbdUL,
  570.    0x4c11db70UL, 0x48d0c6c7UL, 0x4593e01eUL, 0x4152fda9UL,
  571.    0x5f15adacUL, 0x5bd4b01bUL, 0x569796c2UL, 0x52568b75UL,
  572.    0x6a1936c8UL, 0x6ed82b7fUL, 0x639b0da6UL, 0x675a1011UL,
  573.    0x791d4014UL, 0x7ddc5da3UL, 0x709f7b7aUL, 0x745e66cdUL,
  574.    0x9823b6e0UL, 0x9ce2ab57UL, 0x91a18d8eUL, 0x95609039UL,
  575.    0x8b27c03cUL, 0x8fe6dd8bUL, 0x82a5fb52UL, 0x8664e6e5UL,
  576.    0xbe2b5b58UL, 0xbaea46efUL, 0xb7a96036UL, 0xb3687d81UL,
  577.    0xad2f2d84UL, 0xa9ee3033UL, 0xa4ad16eaUL, 0xa06c0b5dUL,
  578.    0xd4326d90UL, 0xd0f37027UL, 0xddb056feUL, 0xd9714b49UL,
  579.    0xc7361b4cUL, 0xc3f706fbUL, 0xceb42022UL, 0xca753d95UL,
  580.    0xf23a8028UL, 0xf6fb9d9fUL, 0xfbb8bb46UL, 0xff79a6f1UL,
  581.    0xe13ef6f4UL, 0xe5ffeb43UL, 0xe8bccd9aUL, 0xec7dd02dUL,
  582.    0x34867077UL, 0x30476dc0UL, 0x3d044b19UL, 0x39c556aeUL,
  583.    0x278206abUL, 0x23431b1cUL, 0x2e003dc5UL, 0x2ac12072UL,
  584.    0x128e9dcfUL, 0x164f8078UL, 0x1b0ca6a1UL, 0x1fcdbb16UL,
  585.    0x018aeb13UL, 0x054bf6a4UL, 0x0808d07dUL, 0x0cc9cdcaUL,
  586.    0x7897ab07UL, 0x7c56b6b0UL, 0x71159069UL, 0x75d48ddeUL,
  587.    0x6b93dddbUL, 0x6f52c06cUL, 0x6211e6b5UL, 0x66d0fb02UL,
  588.    0x5e9f46bfUL, 0x5a5e5b08UL, 0x571d7dd1UL, 0x53dc6066UL,
  589.    0x4d9b3063UL, 0x495a2dd4UL, 0x44190b0dUL, 0x40d816baUL,
  590.    0xaca5c697UL, 0xa864db20UL, 0xa527fdf9UL, 0xa1e6e04eUL,
  591.    0xbfa1b04bUL, 0xbb60adfcUL, 0xb6238b25UL, 0xb2e29692UL,
  592.    0x8aad2b2fUL, 0x8e6c3698UL, 0x832f1041UL, 0x87ee0df6UL,
  593.    0x99a95df3UL, 0x9d684044UL, 0x902b669dUL, 0x94ea7b2aUL,
  594.    0xe0b41de7UL, 0xe4750050UL, 0xe9362689UL, 0xedf73b3eUL,
  595.    0xf3b06b3bUL, 0xf771768cUL, 0xfa325055UL, 0xfef34de2UL,
  596.    0xc6bcf05fUL, 0xc27dede8UL, 0xcf3ecb31UL, 0xcbffd686UL,
  597.    0xd5b88683UL, 0xd1799b34UL, 0xdc3abdedUL, 0xd8fba05aUL,
  598.    0x690ce0eeUL, 0x6dcdfd59UL, 0x608edb80UL, 0x644fc637UL,
  599.    0x7a089632UL, 0x7ec98b85UL, 0x738aad5cUL, 0x774bb0ebUL,
  600.    0x4f040d56UL, 0x4bc510e1UL, 0x46863638UL, 0x42472b8fUL,
  601.    0x5c007b8aUL, 0x58c1663dUL, 0x558240e4UL, 0x51435d53UL,
  602.    0x251d3b9eUL, 0x21dc2629UL, 0x2c9f00f0UL, 0x285e1d47UL,
  603.    0x36194d42UL, 0x32d850f5UL, 0x3f9b762cUL, 0x3b5a6b9bUL,
  604.    0x0315d626UL, 0x07d4cb91UL, 0x0a97ed48UL, 0x0e56f0ffUL,
  605.    0x1011a0faUL, 0x14d0bd4dUL, 0x19939b94UL, 0x1d528623UL,
  606.    0xf12f560eUL, 0xf5ee4bb9UL, 0xf8ad6d60UL, 0xfc6c70d7UL,
  607.    0xe22b20d2UL, 0xe6ea3d65UL, 0xeba91bbcUL, 0xef68060bUL,
  608.    0xd727bbb6UL, 0xd3e6a601UL, 0xdea580d8UL, 0xda649d6fUL,
  609.    0xc423cd6aUL, 0xc0e2d0ddUL, 0xcda1f604UL, 0xc960ebb3UL,
  610.    0xbd3e8d7eUL, 0xb9ff90c9UL, 0xb4bcb610UL, 0xb07daba7UL,
  611.    0xae3afba2UL, 0xaafbe615UL, 0xa7b8c0ccUL, 0xa379dd7bUL,
  612.    0x9b3660c6UL, 0x9ff77d71UL, 0x92b45ba8UL, 0x9675461fUL,
  613.    0x8832161aUL, 0x8cf30badUL, 0x81b02d74UL, 0x857130c3UL,
  614.    0x5d8a9099UL, 0x594b8d2eUL, 0x5408abf7UL, 0x50c9b640UL,
  615.    0x4e8ee645UL, 0x4a4ffbf2UL, 0x470cdd2bUL, 0x43cdc09cUL,
  616.    0x7b827d21UL, 0x7f436096UL, 0x7200464fUL, 0x76c15bf8UL,
  617.    0x68860bfdUL, 0x6c47164aUL, 0x61043093UL, 0x65c52d24UL,
  618.    0x119b4be9UL, 0x155a565eUL, 0x18197087UL, 0x1cd86d30UL,
  619.    0x029f3d35UL, 0x065e2082UL, 0x0b1d065bUL, 0x0fdc1becUL,
  620.    0x3793a651UL, 0x3352bbe6UL, 0x3e119d3fUL, 0x3ad08088UL,
  621.    0x2497d08dUL, 0x2056cd3aUL, 0x2d15ebe3UL, 0x29d4f654UL,
  622.    0xc5a92679UL, 0xc1683bceUL, 0xcc2b1d17UL, 0xc8ea00a0UL,
  623.    0xd6ad50a5UL, 0xd26c4d12UL, 0xdf2f6bcbUL, 0xdbee767cUL,
  624.    0xe3a1cbc1UL, 0xe760d676UL, 0xea23f0afUL, 0xeee2ed18UL,
  625.    0xf0a5bd1dUL, 0xf464a0aaUL, 0xf9278673UL, 0xfde69bc4UL,
  626.    0x89b8fd09UL, 0x8d79e0beUL, 0x803ac667UL, 0x84fbdbd0UL,
  627.    0x9abc8bd5UL, 0x9e7d9662UL, 0x933eb0bbUL, 0x97ffad0cUL,
  628.    0xafb010b1UL, 0xab710d06UL, 0xa6322bdfUL, 0xa2f33668UL,
  629.    0xbcb4666dUL, 0xb8757bdaUL, 0xb5365d03UL, 0xb1f740b4UL
  630. };
  631.  
  632.  
  633. /*---------------------------------------------*/
  634. void initialiseCRC ( void )
  635. {
  636.    globalCrc = 0xffffffffUL;
  637. }
  638.  
  639.  
  640. /*---------------------------------------------*/
  641. UInt32 getFinalCRC ( void )
  642. {
  643.    return ~globalCrc;
  644. }
  645.  
  646.  
  647. /*---------------------------------------------*/
  648. UInt32 getGlobalCRC ( void )
  649. {
  650.    return globalCrc;
  651. }
  652.  
  653.  
  654. /*---------------------------------------------*/
  655. void setGlobalCRC ( UInt32 newCrc )
  656. {
  657.    globalCrc = newCrc;
  658. }
  659.  
  660.  
  661. /*---------------------------------------------*/
  662. #define UPDATE_CRC(crcVar,cha)              \
  663. {                                           \
  664.    crcVar = (crcVar << 8) ^                 \
  665.             crc32Table[(crcVar >> 24) ^     \
  666.                        ((UChar)cha)];       \
  667. }
  668.  
  669.  
  670. /*---------------------------------------------------*/
  671. /*--- Bit stream I/O                              ---*/
  672. /*---------------------------------------------------*/
  673.  
  674.  
  675. UInt32 bsBuff;
  676. Int32  bsLive;
  677. FILE*  bsStream;
  678. Bool   bsWriting;
  679.  
  680.  
  681. /*---------------------------------------------*/
  682. void bsSetStream ( FILE* f, Bool wr )
  683. {
  684.    if (bsStream != NULL) panic ( "bsSetStream" );
  685.    bsStream = f;
  686.    bsLive = 0;
  687.    bsBuff = 0;
  688.    bytesOut = 0;
  689.    bytesIn = 0;
  690.    bsWriting = wr;
  691. }
  692.  
  693.  
  694. /*---------------------------------------------*/
  695. void bsFinishedWithStream ( void )
  696. {
  697.    if (bsWriting)
  698.       while (bsLive > 0) {
  699.          fputc ( (UChar)(bsBuff >> 24), bsStream );
  700.          bsBuff <<= 8;
  701.          bsLive -= 8;
  702.          bytesOut++;
  703.       }
  704.    bsStream = NULL;
  705. }
  706.  
  707.  
  708. /*---------------------------------------------*/
  709. #define bsNEEDR(nz)                           \
  710. {                                             \
  711.    while (bsLive < nz) {                      \
  712.       Int32 zzi = fgetc ( bsStream );         \
  713.       if (zzi == EOF) compressedStreamEOF();  \
  714.       bsBuff = (bsBuff << 8) | (zzi & 0xffL); \
  715.       bsLive += 8;                            \
  716.    }                                          \
  717. }
  718.  
  719.  
  720. /*---------------------------------------------*/
  721. #define bsNEEDW(nz)                           \
  722. {                                             \
  723.    while (bsLive >= 8) {                      \
  724.       fputc ( (UChar)(bsBuff >> 24),          \
  725.                bsStream );                    \
  726.       bsBuff <<= 8;                           \
  727.       bsLive -= 8;                            \
  728.       bytesOut++;                             \
  729.    }                                          \
  730. }
  731.  
  732.  
  733. /*---------------------------------------------*/
  734. #define bsR1(vz)                              \
  735. {                                             \
  736.    bsNEEDR(1);                                \
  737.    vz = (bsBuff >> (bsLive-1)) & 1;           \
  738.    bsLive--;                                  \
  739. }
  740.  
  741.  
  742. /*---------------------------------------------*/
  743. INLINE UInt32 bsR ( Int32 n )
  744. {
  745.    UInt32 v;
  746.    bsNEEDR ( n );
  747.    v = (bsBuff >> (bsLive-n)) & ((1 << n)-1);
  748.    bsLive -= n;
  749.    return v;
  750. }
  751.  
  752.  
  753. /*---------------------------------------------*/
  754. INLINE void bsW ( Int32 n, UInt32 v )
  755. {
  756.    bsNEEDW ( n );
  757.    bsBuff |= (v << (32 - bsLive - n));
  758.    bsLive += n;
  759. }
  760.  
  761.  
  762. /*---------------------------------------------*/
  763. UChar bsGetUChar ( void )
  764. {
  765.    return (UChar)bsR(8);
  766. }
  767.  
  768.  
  769. /*---------------------------------------------*/
  770. void bsPutUChar ( UChar c )
  771. {
  772.    bsW(8, (UInt32)c );
  773. }
  774.  
  775.  
  776. /*---------------------------------------------*/
  777. Int32 bsGetUInt32 ( void )
  778. {
  779.    UInt32 u;
  780.    u = 0;
  781.    u = (u << 8) | bsR(8);
  782.    u = (u << 8) | bsR(8);
  783.    u = (u << 8) | bsR(8);
  784.    u = (u << 8) | bsR(8);
  785.    return u;
  786. }
  787.  
  788.  
  789. /*---------------------------------------------*/
  790. UInt32 bsGetIntVS ( UInt32 numBits )
  791. {
  792.    return (UInt32)bsR(numBits);
  793. }
  794.  
  795.  
  796. /*---------------------------------------------*/
  797. UInt32 bsGetInt32 ( void )
  798. {
  799.    return (Int32)bsGetUInt32();
  800. }
  801.  
  802.  
  803. /*---------------------------------------------*/
  804. void bsPutUInt32 ( UInt32 u )
  805. {
  806.    bsW ( 8, (u >> 24) & 0xffL );
  807.    bsW ( 8, (u >> 16) & 0xffL );
  808.    bsW ( 8, (u >>  8) & 0xffL );
  809.    bsW ( 8,  u        & 0xffL );
  810. }
  811.  
  812.  
  813. /*---------------------------------------------*/
  814. void bsPutInt32 ( Int32 c )
  815. {
  816.    bsPutUInt32 ( (UInt32)c );
  817. }
  818.  
  819.  
  820. /*---------------------------------------------*/
  821. void bsPutIntVS ( Int32 numBits, UInt32 c )
  822. {
  823.    bsW ( numBits, c );
  824. }
  825.  
  826.  
  827. /*---------------------------------------------------*/
  828. /*--- Huffman coding low-level stuff              ---*/
  829. /*---------------------------------------------------*/
  830.  
  831. #define WEIGHTOF(zz0)  ((zz0) & 0xffffff00)
  832. #define DEPTHOF(zz1)   ((zz1) & 0x000000ff)
  833. #define MYMAX(zz2,zz3) ((zz2) > (zz3) ? (zz2) : (zz3))
  834.  
  835. #define ADDWEIGHTS(zw1,zw2)                           \
  836.    (WEIGHTOF(zw1)+WEIGHTOF(zw2)) |                    \
  837.    (1 + MYMAX(DEPTHOF(zw1),DEPTHOF(zw2)))
  838.  
  839. #define UPHEAP(z)                                     \
  840. {                                                     \
  841.    Int32 zz, tmp;                                     \
  842.    zz = z; tmp = heap[zz];                            \
  843.    while (weight[tmp] < weight[heap[zz >> 1]]) {      \
  844.       heap[zz] = heap[zz >> 1];                       \
  845.       zz >>= 1;                                       \
  846.    }                                                  \
  847.    heap[zz] = tmp;                                    \
  848. }
  849.  
  850. #define DOWNHEAP(z)                                   \
  851. {                                                     \
  852.    Int32 zz, yy, tmp;                                 \
  853.    zz = z; tmp = heap[zz];                            \
  854.    while (True) {                                     \
  855.       yy = zz << 1;                                   \
  856.       if (yy > nHeap) break;                          \
  857.       if (yy < nHeap &&                               \
  858.           weight[heap[yy+1]] < weight[heap[yy]])      \
  859.          yy++;                                        \
  860.       if (weight[tmp] < weight[heap[yy]]) break;      \
  861.       heap[zz] = heap[yy];                            \
  862.       zz = yy;                                        \
  863.    }                                                  \
  864.    heap[zz] = tmp;                                    \
  865. }
  866.  
  867.  
  868. /*---------------------------------------------*/
  869. void hbMakeCodeLengths ( UChar *len,
  870.                          Int32 *freq,
  871.                          Int32 alphaSize,
  872.                          Int32 maxLen )
  873. {
  874.    /*--
  875.       Nodes and heap entries run from 1.  Entry 0
  876.       for both the heap and nodes is a sentinel.
  877.    --*/
  878.    Int32 nNodes, nHeap, n1, n2, i, j, k;
  879.    Bool  tooLong;
  880.  
  881.    Int32 heap   [ MAX_ALPHA_SIZE + 2 ];
  882.    Int32 weight [ MAX_ALPHA_SIZE * 2 ];
  883.    Int32 parent [ MAX_ALPHA_SIZE * 2 ];
  884.  
  885.    for (i = 0; i < alphaSize; i++)
  886.       weight[i+1] = (freq[i] == 0 ? 1 : freq[i]) << 8;
  887.  
  888.    while (True) {
  889.  
  890.       nNodes = alphaSize;
  891.       nHeap = 0;
  892.  
  893.       heap[0] = 0;
  894.       weight[0] = 0;
  895.       parent[0] = -2;
  896.  
  897.       for (i = 1; i <= alphaSize; i++) {
  898.          parent[i] = -1;
  899.          nHeap++;
  900.          heap[nHeap] = i;
  901.          UPHEAP(nHeap);
  902.       }
  903.       if (!(nHeap < (MAX_ALPHA_SIZE+2)))
  904.          panic ( "hbMakeCodeLengths(1)" );
  905.  
  906.       while (nHeap > 1) {
  907.          n1 = heap[1]; heap[1] = heap[nHeap]; nHeap--; DOWNHEAP(1);
  908.          n2 = heap[1]; heap[1] = heap[nHeap]; nHeap--; DOWNHEAP(1);
  909.          nNodes++;
  910.          parent[n1] = parent[n2] = nNodes;
  911.          weight[nNodes] = ADDWEIGHTS(weight[n1], weight[n2]);
  912.          parent[nNodes] = -1;
  913.          nHeap++;
  914.          heap[nHeap] = nNodes;
  915.          UPHEAP(nHeap);
  916.       }
  917.       if (!(nNodes < (MAX_ALPHA_SIZE * 2)))
  918.          panic ( "hbMakeCodeLengths(2)" );
  919.  
  920.       tooLong = False;
  921.       for (i = 1; i <= alphaSize; i++) {
  922.          j = 0;
  923.          k = i;
  924.          while (parent[k] >= 0) { k = parent[k]; j++; }
  925.          len[i-1] = j;
  926.          if (j > maxLen) tooLong = True;
  927.       }
  928.  
  929.       if (! tooLong) break;
  930.  
  931.       for (i = 1; i < alphaSize; i++) {
  932.          j = weight[i] >> 8;
  933.          j = 1 + (j / 2);
  934.          weight[i] = j << 8;
  935.       }
  936.    }
  937. }
  938.  
  939.  
  940. /*---------------------------------------------*/
  941. void hbAssignCodes ( Int32 *code,
  942.                      UChar *length,
  943.                      Int32 minLen,
  944.                      Int32 maxLen,
  945.                      Int32 alphaSize )
  946. {
  947.    Int32 n, vec, i;
  948.  
  949.    vec = 0;
  950.    for (n = minLen; n <= maxLen; n++) {
  951.       for (i = 0; i < alphaSize; i++)
  952.          if (length[i] == n) { code[i] = vec; vec++; };
  953.       vec <<= 1;
  954.    }
  955. }
  956.  
  957.  
  958. /*---------------------------------------------*/
  959. void hbCreateDecodeTables ( Int32 *limit,
  960.                             Int32 *base,
  961.                             Int32 *perm,
  962.                             UChar *length,
  963.                             Int32 minLen,
  964.                             Int32 maxLen,
  965.                             Int32 alphaSize )
  966. {
  967.    Int32 pp, i, j, vec;
  968.  
  969.    pp = 0;
  970.    for (i = minLen; i <= maxLen; i++)
  971.       for (j = 0; j < alphaSize; j++)
  972.          if (length[j] == i) { perm[pp] = j; pp++; };
  973.  
  974.    for (i = 0; i < MAX_CODE_LEN; i++) base[i] = 0;
  975.    for (i = 0; i < alphaSize; i++) base[length[i]+1]++;
  976.  
  977.    for (i = 1; i < MAX_CODE_LEN; i++) base[i] += base[i-1];
  978.  
  979.    for (i = 0; i < MAX_CODE_LEN; i++) limit[i] = 0;
  980.    vec = 0;
  981.  
  982.    for (i = minLen; i <= maxLen; i++) {
  983.       vec += (base[i+1] - base[i]);
  984.       limit[i] = vec-1;
  985.       vec <<= 1;
  986.    }
  987.    for (i = minLen + 1; i <= maxLen; i++)
  988.       base[i] = ((limit[i-1] + 1) << 1) - base[i];
  989. }
  990.  
  991.  
  992.  
  993. /*---------------------------------------------------*/
  994. /*--- Undoing the reversible transformation       ---*/
  995. /*---------------------------------------------------*/
  996.  
  997. /*---------------------------------------------*/
  998. #define SET_LL4(i,n)                                          \
  999.    { if (((i) & 0x1) == 0)                                    \
  1000.         ll4[(i) >> 1] = (ll4[(i) >> 1] & 0xf0) | (n); else    \
  1001.         ll4[(i) >> 1] = (ll4[(i) >> 1] & 0x0f) | ((n) << 4);  \
  1002.    }
  1003.  
  1004. #define GET_LL4(i)                             \
  1005.     (((UInt32)(ll4[(i) >> 1])) >> (((i) << 2) & 0x4) & 0xF)
  1006.  
  1007. #define SET_LL(i,n)                       \
  1008.    { ll16[i] = (UInt16)(n & 0x0000ffff);  \
  1009.      SET_LL4(i, n >> 16);                 \
  1010.    }
  1011.  
  1012. #define GET_LL(i) \
  1013.    (((UInt32)ll16[i]) | (GET_LL4(i) << 16))
  1014.  
  1015.  
  1016. /*---------------------------------------------*/
  1017. /*--
  1018.   Manage memory for compression/decompression.
  1019.   When compressing, a single block size applies to
  1020.   all files processed, and that's set when the
  1021.   program starts.  But when decompressing, each file
  1022.   processed could have been compressed with a
  1023.   different block size, so we may have to free
  1024.   and reallocate on a per-file basis.
  1025.  
  1026.   A call with argument of zero means
  1027.   `free up everything.'  And a value of zero for
  1028.   blockSize100k means no memory is currently allocated.
  1029. --*/
  1030.  
  1031.  
  1032. /*---------------------------------------------*/
  1033. void allocateCompressStructures ( void )
  1034. {
  1035.    Int32 n  = 100000 * blockSize100k;
  1036.    block    = malloc ( (n + 1 + NUM_OVERSHOOT_BYTES) * sizeof(UChar) );
  1037.    quadrant = malloc ( (n     + NUM_OVERSHOOT_BYTES) * sizeof(Int16) );
  1038.    zptr     = malloc ( n                             * sizeof(Int32) );
  1039.    ftab     = malloc ( 65537                         * sizeof(Int32) );
  1040.  
  1041.    if (block == NULL || quadrant == NULL ||
  1042.        zptr == NULL  || ftab == NULL) {
  1043.       Int32 totalDraw
  1044.          = (n + 1 + NUM_OVERSHOOT_BYTES) * sizeof(UChar) +
  1045.            (n     + NUM_OVERSHOOT_BYTES) * sizeof(Int16) +
  1046.            n                             * sizeof(Int32) +
  1047.            65537                         * sizeof(Int32);
  1048.  
  1049.       compressOutOfMemory ( totalDraw, n );
  1050.    }
  1051.  
  1052.    /*--
  1053.       Since we want valid indexes for block of
  1054.       -1 to n + NUM_OVERSHOOT_BYTES - 1
  1055.       inclusive.
  1056.    --*/
  1057.    block++;
  1058.  
  1059.    /*--
  1060.       The back end needs a place to store the MTF values
  1061.       whilst it calculates the coding tables.  We could
  1062.       put them in the zptr array.  However, these values
  1063.       will fit in a short, so we overlay szptr at the
  1064.       start of zptr, in the hope of reducing the number
  1065.       of cache misses induced by the multiple traversals
  1066.       of the MTF values when calculating coding tables.
  1067.       Seems to improve compression speed by about 1%.
  1068.    --*/
  1069.    szptr = (UInt16*)zptr;
  1070. }
  1071.  
  1072.  
  1073. /*---------------------------------------------*/
  1074. void setDecompressStructureSizes ( Int32 newSize100k )
  1075. {
  1076.    if (! (0 <= newSize100k   && newSize100k   <= 9 &&
  1077.           0 <= blockSize100k && blockSize100k <= 9))
  1078.       panic ( "setDecompressStructureSizes" );
  1079.  
  1080.    if (newSize100k == blockSize100k) return;
  1081.  
  1082.    blockSize100k = newSize100k;
  1083.  
  1084.    if (ll16  != NULL) free ( ll16  );
  1085.    if (ll4   != NULL) free ( ll4   );
  1086.    if (ll8   != NULL) free ( ll8   );
  1087.    if (tt    != NULL) free ( tt    );
  1088.  
  1089.    if (newSize100k == 0) return;
  1090.  
  1091.    if (smallMode) {
  1092.  
  1093.       Int32 n = 100000 * newSize100k;
  1094.       ll16    = malloc ( n * sizeof(UInt16) );
  1095.       ll4     = malloc ( ((n+1) >> 1) * sizeof(UChar) );
  1096.  
  1097.       if (ll4 == NULL || ll16 == NULL) {
  1098.          Int32 totalDraw
  1099.             = n * sizeof(Int16) + ((n+1) >> 1) * sizeof(UChar);
  1100.          uncompressOutOfMemory ( totalDraw, n );
  1101.       }
  1102.  
  1103.    } else {
  1104.  
  1105.       Int32 n = 100000 * newSize100k;
  1106.       ll8     = malloc ( n * sizeof(UChar) );
  1107.       tt      = malloc ( n * sizeof(Int32) );
  1108.  
  1109.       if (ll8 == NULL || tt == NULL) {
  1110.          Int32 totalDraw
  1111.             = n * sizeof(UChar) + n * sizeof(UInt32);
  1112.          uncompressOutOfMemory ( totalDraw, n );
  1113.       }
  1114.  
  1115.    }
  1116. }
  1117.  
  1118.  
  1119.  
  1120. /*---------------------------------------------------*/
  1121. /*--- The new back end                            ---*/
  1122. /*---------------------------------------------------*/
  1123.  
  1124. /*---------------------------------------------*/
  1125. void makeMaps ( void )
  1126. {
  1127.    Int32 i;
  1128.    nInUse = 0;
  1129.    for (i = 0; i < 256; i++)
  1130.       if (inUse[i]) {
  1131.          seqToUnseq[nInUse] = i;
  1132.          unseqToSeq[i] = nInUse;
  1133.          nInUse++;
  1134.       }
  1135. }
  1136.  
  1137.  
  1138. /*---------------------------------------------*/
  1139. void generateMTFValues ( void )
  1140. {
  1141.    UChar  yy[256];
  1142.    Int32  i, j;
  1143.    UChar  tmp;
  1144.    UChar  tmp2;
  1145.    Int32  zPend;
  1146.    Int32  wr;
  1147.    Int32  EOB;
  1148.  
  1149.    makeMaps();
  1150.    EOB = nInUse+1;
  1151.  
  1152.    for (i = 0; i <= EOB; i++) mtfFreq[i] = 0;
  1153.  
  1154.    wr = 0;
  1155.    zPend = 0;
  1156.    for (i = 0; i < nInUse; i++) yy[i] = (UChar) i;
  1157.  
  1158.  
  1159.    for (i = 0; i <= last; i++) {
  1160.       UChar ll_i;
  1161.  
  1162.       #if DEBUG
  1163.          assert (wr <= i);
  1164.       #endif
  1165.  
  1166.       ll_i = unseqToSeq[block[zptr[i] - 1]];
  1167.       #if DEBUG
  1168.          assert (ll_i < nInUse);
  1169.       #endif
  1170.  
  1171.       j = 0;
  1172.       tmp = yy[j];
  1173.       while ( ll_i != tmp ) {
  1174.          j++;
  1175.          tmp2 = tmp;
  1176.          tmp = yy[j];
  1177.          yy[j] = tmp2;
  1178.       };
  1179.       yy[0] = tmp;
  1180.  
  1181.       if (j == 0) {
  1182.          zPend++;
  1183.       } else {
  1184.          if (zPend > 0) {
  1185.             zPend--;
  1186.             while (True) {
  1187.                switch (zPend % 2) {
  1188.                   case 0: szptr[wr] = RUNA; wr++; mtfFreq[RUNA]++; break;
  1189.                   case 1: szptr[wr] = RUNB; wr++; mtfFreq[RUNB]++; break;
  1190.                };
  1191.                if (zPend < 2) break;
  1192.                zPend = (zPend - 2) / 2;
  1193.             };
  1194.             zPend = 0;
  1195.          }
  1196.          szptr[wr] = j+1; wr++; mtfFreq[j+1]++;
  1197.       }
  1198.    }
  1199.  
  1200.    if (zPend > 0) {
  1201.       zPend--;
  1202.       while (True) {
  1203.          switch (zPend % 2) {
  1204.             case 0:  szptr[wr] = RUNA; wr++; mtfFreq[RUNA]++; break;
  1205.             case 1:  szptr[wr] = RUNB; wr++; mtfFreq[RUNB]++; break;
  1206.          };
  1207.          if (zPend < 2) break;
  1208.          zPend = (zPend - 2) / 2;
  1209.       };
  1210.    }
  1211.  
  1212.    szptr[wr] = EOB; wr++; mtfFreq[EOB]++;
  1213.  
  1214.    nMTF = wr;
  1215. }
  1216.  
  1217.  
  1218. /*---------------------------------------------*/
  1219. #define LESSER_ICOST  0
  1220. #define GREATER_ICOST 15
  1221.  
  1222. void sendMTFValues ( void )
  1223. {
  1224.    Int32 v, t, i, j, gs, ge, totc, bt, bc, iter;
  1225.    Int32 nSelectors, alphaSize, minLen, maxLen, selCtr;
  1226.    Int32 nGroups, nBytes;
  1227.  
  1228.    /*--
  1229.    UChar  len [N_GROUPS][MAX_ALPHA_SIZE];
  1230.    is a global since the decoder also needs it.
  1231.  
  1232.    Int32  code[N_GROUPS][MAX_ALPHA_SIZE];
  1233.    Int32  rfreq[N_GROUPS][MAX_ALPHA_SIZE];
  1234.    are also globals only used in this proc.
  1235.    Made global to keep stack frame size small.
  1236.    --*/
  1237.  
  1238.  
  1239.    UInt16 cost[N_GROUPS];
  1240.    Int32  fave[N_GROUPS];
  1241.  
  1242.    if (verbosity >= 3)
  1243.       fprintf ( stderr,
  1244.                 "      %d in block, %d after MTF & 1-2 coding, %d+2 syms in use\n",
  1245.                 last+1, nMTF, nInUse );
  1246.  
  1247.    alphaSize = nInUse+2;
  1248.    for (t = 0; t < N_GROUPS; t++)
  1249.       for (v = 0; v < alphaSize; v++)
  1250.          len[t][v] = GREATER_ICOST;
  1251.  
  1252.    /*--- Decide how many coding tables to use ---*/
  1253.    if (nMTF <= 0) panic ( "sendMTFValues(0)" );
  1254.    if (nMTF < 200) nGroups = 2; else
  1255.    if (nMTF < 800) nGroups = 4; else
  1256.                    nGroups = 6;
  1257.  
  1258.    /*--- Generate an initial set of coding tables ---*/
  1259.    {
  1260.       Int32 nPart, remF, tFreq, aFreq;
  1261.  
  1262.       nPart = nGroups;
  1263.       remF  = nMTF;
  1264.       gs = 0;
  1265.       while (nPart > 0) {
  1266.          tFreq = remF / nPart;
  1267.          ge = gs-1;
  1268.          aFreq = 0;
  1269.          while (aFreq < tFreq && ge < alphaSize-1) {
  1270.             ge++;
  1271.             aFreq += mtfFreq[ge];
  1272.          }
  1273.  
  1274.          if (ge > gs
  1275.              && nPart != nGroups && nPart != 1
  1276.              && ((nGroups-nPart) % 2 == 1)) {
  1277.             aFreq -= mtfFreq[ge];
  1278.             ge--;
  1279.          }
  1280.  
  1281.          if (verbosity >= 3)
  1282.             fprintf ( stderr,
  1283.                       "      initial group %d, [%d .. %d], has %d syms (%4.1f%%)\n",
  1284.                               nPart, gs, ge, aFreq,
  1285.                               (100.0 * (float)aFreq) / (float)nMTF );
  1286.  
  1287.          for (v = 0; v < alphaSize; v++)
  1288.             if (v >= gs && v <= ge)
  1289.                len[nPart-1][v] = LESSER_ICOST; else
  1290.                len[nPart-1][v] = GREATER_ICOST;
  1291.  
  1292.          nPart--;
  1293.          gs = ge+1;
  1294.          remF -= aFreq;
  1295.       }
  1296.    }
  1297.  
  1298.    /*---
  1299.       Iterate up to N_ITERS times to improve the tables.
  1300.    ---*/
  1301.    for (iter = 0; iter < N_ITERS; iter++) {
  1302.  
  1303.       for (t = 0; t < nGroups; t++) fave[t] = 0;
  1304.  
  1305.       for (t = 0; t < nGroups; t++)
  1306.          for (v = 0; v < alphaSize; v++)
  1307.             rfreq[t][v] = 0;
  1308.  
  1309.       nSelectors = 0;
  1310.       totc = 0;
  1311.       gs = 0;
  1312.       while (True) {
  1313.  
  1314.          /*--- Set group start & end marks. --*/
  1315.          if (gs >= nMTF) break;
  1316.          ge = gs + G_SIZE - 1;
  1317.          if (ge >= nMTF) ge = nMTF-1;
  1318.  
  1319.          /*--
  1320.             Calculate the cost of this group as coded
  1321.             by each of the coding tables.
  1322.          --*/
  1323.          for (t = 0; t < nGroups; t++) cost[t] = 0;
  1324.  
  1325.          if (nGroups == 6) {
  1326.             register UInt16 cost0, cost1, cost2, cost3, cost4, cost5;
  1327.             cost0 = cost1 = cost2 = cost3 = cost4 = cost5 = 0;
  1328.             for (i = gs; i <= ge; i++) {
  1329.                UInt16 icv = szptr[i];
  1330.                cost0 += len[0][icv];
  1331.                cost1 += len[1][icv];
  1332.                cost2 += len[2][icv];
  1333.                cost3 += len[3][icv];
  1334.                cost4 += len[4][icv];
  1335.                cost5 += len[5][icv];
  1336.             }
  1337.             cost[0] = cost0; cost[1] = cost1; cost[2] = cost2;
  1338.             cost[3] = cost3; cost[4] = cost4; cost[5] = cost5;
  1339.          } else {
  1340.             for (i = gs; i <= ge; i++) {
  1341.                UInt16 icv = szptr[i];
  1342.                for (t = 0; t < nGroups; t++) cost[t] += len[t][icv];
  1343.             }
  1344.          }
  1345.  
  1346.          /*--
  1347.             Find the coding table which is best for this group,
  1348.             and record its identity in the selector table.
  1349.          --*/
  1350.          bc = 999999999; bt = -1;
  1351.          for (t = 0; t < nGroups; t++)
  1352.             if (cost[t] < bc) { bc = cost[t]; bt = t; };
  1353.          totc += bc;
  1354.          fave[bt]++;
  1355.          selector[nSelectors] = bt;
  1356.          nSelectors++;
  1357.  
  1358.          /*--
  1359.             Increment the symbol frequencies for the selected table.
  1360.           --*/
  1361.          for (i = gs; i <= ge; i++)
  1362.             rfreq[bt][ szptr[i] ]++;
  1363.  
  1364.          gs = ge+1;
  1365.       }
  1366.       if (verbosity >= 3) {
  1367.          fprintf ( stderr,
  1368.                    "      pass %d: size is %d, grp uses are ",
  1369.                    iter+1, totc/8 );
  1370.          for (t = 0; t < nGroups; t++)
  1371.             fprintf ( stderr, "%d ", fave[t] );
  1372.          fprintf ( stderr, "\n" );
  1373.       }
  1374.  
  1375.       /*--
  1376.         Recompute the tables based on the accumulated frequencies.
  1377.       --*/
  1378.       for (t = 0; t < nGroups; t++)
  1379.          hbMakeCodeLengths ( &len[t][0], &rfreq[t][0], alphaSize, 20 );
  1380.    }
  1381.  
  1382.  
  1383.    if (!(nGroups < 8)) panic ( "sendMTFValues(1)" );
  1384.    if (!(nSelectors < 32768 &&
  1385.          nSelectors <= (2 + (900000 / G_SIZE))))
  1386.                        panic ( "sendMTFValues(2)" );
  1387.  
  1388.  
  1389.    /*--- Compute MTF values for the selectors. ---*/
  1390.    {
  1391.       UChar pos[N_GROUPS], ll_i, tmp2, tmp;
  1392.       for (i = 0; i < nGroups; i++) pos[i] = i;
  1393.       for (i = 0; i < nSelectors; i++) {
  1394.          ll_i = selector[i];
  1395.          j = 0;
  1396.          tmp = pos[j];
  1397.          while ( ll_i != tmp ) {
  1398.             j++;
  1399.             tmp2 = tmp;
  1400.             tmp = pos[j];
  1401.             pos[j] = tmp2;
  1402.          };
  1403.          pos[0] = tmp;
  1404.          selectorMtf[i] = j;
  1405.       }
  1406.    };
  1407.  
  1408.    /*--- Assign actual codes for the tables. --*/
  1409.    for (t = 0; t < nGroups; t++) {
  1410.       minLen = 32;
  1411.       maxLen = 0;
  1412.       for (i = 0; i < alphaSize; i++) {
  1413.          if (len[t][i] > maxLen) maxLen = len[t][i];
  1414.          if (len[t][i] < minLen) minLen = len[t][i];
  1415.       }
  1416.       if (maxLen > 20) panic ( "sendMTFValues(3)" );
  1417.       if (minLen < 1)  panic ( "sendMTFValues(4)" );
  1418.       hbAssignCodes ( &code[t][0], &len[t][0],
  1419.                       minLen, maxLen, alphaSize );
  1420.    }
  1421.  
  1422.    /*--- Transmit the mapping table. ---*/
  1423.    {
  1424.       Bool inUse16[16];
  1425.       for (i = 0; i < 16; i++) {
  1426.           inUse16[i] = False;
  1427.           for (j = 0; j < 16; j++)
  1428.              if (inUse[i * 16 + j]) inUse16[i] = True;
  1429.       }
  1430.  
  1431.       nBytes = bytesOut;
  1432.       for (i = 0; i < 16; i++)
  1433.          if (inUse16[i]) bsW(1,1); else bsW(1,0);
  1434.  
  1435.       for (i = 0; i < 16; i++)
  1436.          if (inUse16[i])
  1437.             for (j = 0; j < 16; j++)
  1438.                if (inUse[i * 16 + j]) bsW(1,1); else bsW(1,0);
  1439.  
  1440.       if (verbosity >= 3)
  1441.          fprintf ( stderr, "      bytes: mapping %d, ", bytesOut-nBytes );
  1442.    }
  1443.  
  1444.    /*--- Now the selectors. ---*/
  1445.    nBytes = bytesOut;
  1446.    bsW ( 3, nGroups );
  1447.    bsW ( 15, nSelectors );
  1448.    for (i = 0; i < nSelectors; i++) {
  1449.       for (j = 0; j < selectorMtf[i]; j++) bsW(1,1);
  1450.       bsW(1,0);
  1451.    }
  1452.    if (verbosity >= 3)
  1453.       fprintf ( stderr, "selectors %d, ", bytesOut-nBytes );
  1454.  
  1455.    /*--- Now the coding tables. ---*/
  1456.    nBytes = bytesOut;
  1457.  
  1458.    for (t = 0; t < nGroups; t++) {
  1459.       Int32 curr = len[t][0];
  1460.       bsW ( 5, curr );
  1461.       for (i = 0; i < alphaSize; i++) {
  1462.          while (curr < len[t][i]) { bsW(2,2); curr++; /* 10 */ };
  1463.          while (curr > len[t][i]) { bsW(2,3); curr--; /* 11 */ };
  1464.          bsW ( 1, 0 );
  1465.       }
  1466.    }
  1467.  
  1468.    if (verbosity >= 3)
  1469.       fprintf ( stderr, "code lengths %d, ", bytesOut-nBytes );
  1470.  
  1471.    /*--- And finally, the block data proper ---*/
  1472.    nBytes = bytesOut;
  1473.    selCtr = 0;
  1474.    gs = 0;
  1475.    while (True) {
  1476.       if (gs >= nMTF) break;
  1477.       ge = gs + G_SIZE - 1;
  1478.       if (ge >= nMTF) ge = nMTF-1;
  1479.       for (i = gs; i <= ge; i++) {
  1480.          #if DEBUG
  1481.             assert (selector[selCtr] < nGroups);
  1482.          #endif
  1483.          bsW ( len  [selector[selCtr]] [szptr[i]],
  1484.                code [selector[selCtr]] [szptr[i]] );
  1485.       }
  1486.  
  1487.       gs = ge+1;
  1488.       selCtr++;
  1489.    }
  1490.    if (!(selCtr == nSelectors)) panic ( "sendMTFValues(5)" );
  1491.  
  1492.    if (verbosity >= 3)
  1493.       fprintf ( stderr, "codes %d\n", bytesOut-nBytes );
  1494. }
  1495.  
  1496.  
  1497. /*---------------------------------------------*/
  1498. void moveToFrontCodeAndSend ( void )
  1499. {
  1500.    bsPutIntVS ( 24, origPtr );
  1501.    generateMTFValues();
  1502.    sendMTFValues();
  1503. }
  1504.  
  1505.  
  1506. /*---------------------------------------------*/
  1507. void recvDecodingTables ( void )
  1508. {
  1509.    Int32 i, j, t, nGroups, nSelectors, alphaSize;
  1510.    Int32 minLen, maxLen;
  1511.    Bool inUse16[16];
  1512.  
  1513.    /*--- Receive the mapping table ---*/
  1514.    for (i = 0; i < 16; i++)
  1515.       if (bsR(1) == 1)
  1516.          inUse16[i] = True; else
  1517.          inUse16[i] = False;
  1518.  
  1519.    for (i = 0; i < 256; i++) inUse[i] = False;
  1520.  
  1521.    for (i = 0; i < 16; i++)
  1522.       if (inUse16[i])
  1523.          for (j = 0; j < 16; j++)
  1524.             if (bsR(1) == 1) inUse[i * 16 + j] = True;
  1525.  
  1526.    makeMaps();
  1527.    alphaSize = nInUse+2;
  1528.  
  1529.    /*--- Now the selectors ---*/
  1530.    nGroups = bsR ( 3 );
  1531.    nSelectors = bsR ( 15 );
  1532.    for (i = 0; i < nSelectors; i++) {
  1533.       j = 0;
  1534.       while (bsR(1) == 1) j++;
  1535.       selectorMtf[i] = j;
  1536.    }
  1537.  
  1538.    /*--- Undo the MTF values for the selectors. ---*/
  1539.    {
  1540.       UChar pos[N_GROUPS], tmp, v;
  1541.       for (v = 0; v < nGroups; v++) pos[v] = v;
  1542.  
  1543.       for (i = 0; i < nSelectors; i++) {
  1544.          v = selectorMtf[i];
  1545.          tmp = pos[v];
  1546.          while (v > 0) { pos[v] = pos[v-1]; v--; }
  1547.          pos[0] = tmp;
  1548.          selector[i] = tmp;
  1549.       }
  1550.    }
  1551.  
  1552.    /*--- Now the coding tables ---*/
  1553.    for (t = 0; t < nGroups; t++) {
  1554.       Int32 curr = bsR ( 5 );
  1555.       for (i = 0; i < alphaSize; i++) {
  1556.          while (bsR(1) == 1) {
  1557.             if (bsR(1) == 0) curr++; else curr--;
  1558.          }
  1559.          len[t][i] = curr;
  1560.       }
  1561.    }
  1562.  
  1563.    /*--- Create the Huffman decoding tables ---*/
  1564.    for (t = 0; t < nGroups; t++) {
  1565.       minLen = 32;
  1566.       maxLen = 0;
  1567.       for (i = 0; i < alphaSize; i++) {
  1568.          if (len[t][i] > maxLen) maxLen = len[t][i];
  1569.          if (len[t][i] < minLen) minLen = len[t][i];
  1570.       }
  1571.       hbCreateDecodeTables (
  1572.          &limit[t][0], &base[t][0], &perm[t][0], &len[t][0],
  1573.          minLen, maxLen, alphaSize
  1574.       );
  1575.       minLens[t] = minLen;
  1576.    }
  1577. }
  1578.  
  1579.  
  1580. /*---------------------------------------------*/
  1581. #define GET_MTF_VAL(lval)                 \
  1582. {                                         \
  1583.    Int32 zt, zn, zvec, zj;                \
  1584.    if (groupPos == 0) {                   \
  1585.       groupNo++;                          \
  1586.       groupPos = G_SIZE;                  \
  1587.    }                                      \
  1588.    groupPos--;                            \
  1589.    zt = selector[groupNo];                \
  1590.    zn = minLens[zt];                      \
  1591.    zvec = bsR ( zn );                     \
  1592.    while (zvec > limit[zt][zn]) {         \
  1593.       zn++; bsR1(zj);                     \
  1594.       zvec = (zvec << 1) | zj;            \
  1595.    };                                     \
  1596.    lval = perm[zt][zvec - base[zt][zn]];  \
  1597. }
  1598.  
  1599.  
  1600. /*---------------------------------------------*/
  1601. void getAndMoveToFrontDecode ( void )
  1602. {
  1603.    UChar  yy[256];
  1604.    Int32  i, j, nextSym, limitLast;
  1605.    Int32  EOB, groupNo, groupPos;
  1606.  
  1607.    limitLast = 100000 * blockSize100k;
  1608.    origPtr   = bsGetIntVS ( 24 );
  1609.  
  1610.    recvDecodingTables();
  1611.    EOB      = nInUse+1;
  1612.    groupNo  = -1;
  1613.    groupPos = 0;
  1614.  
  1615.    /*--
  1616.       Setting up the unzftab entries here is not strictly
  1617.       necessary, but it does save having to do it later
  1618.       in a separate pass, and so saves a block's worth of
  1619.       cache misses.
  1620.    --*/
  1621.    for (i = 0; i <= 255; i++) unzftab[i] = 0;
  1622.  
  1623.    for (i = 0; i <= 255; i++) yy[i] = (UChar) i;
  1624.  
  1625.    last = -1;
  1626.  
  1627.    GET_MTF_VAL(nextSym);
  1628.  
  1629.    while (True) {
  1630.  
  1631.       if (nextSym == EOB) break;
  1632.  
  1633.       if (nextSym == RUNA || nextSym == RUNB) {
  1634.          UChar ch;
  1635.          Int32 s = -1;
  1636.          Int32 N = 1;
  1637.          do {
  1638.             if (nextSym == RUNA) s = s + (0+1) * N; else
  1639.             if (nextSym == RUNB) s = s + (1+1) * N;
  1640.             N = N * 2;
  1641.             GET_MTF_VAL(nextSym);
  1642.          }
  1643.             while (nextSym == RUNA || nextSym == RUNB);
  1644.  
  1645.          s++;
  1646.          ch = seqToUnseq[yy[0]];
  1647.          unzftab[ch] += s;
  1648.  
  1649.          if (smallMode)
  1650.             while (s > 0) {
  1651.                last++;
  1652.                ll16[last] = ch;
  1653.                s--;
  1654.             }
  1655.          else
  1656.             while (s > 0) {
  1657.                last++;
  1658.                ll8[last] = ch;
  1659.                s--;
  1660.             };
  1661.  
  1662.          if (last >= limitLast) blockOverrun();
  1663.          continue;
  1664.  
  1665.       } else {
  1666.  
  1667.          UChar tmp;
  1668.          last++; if (last >= limitLast) blockOverrun();
  1669.  
  1670.          tmp = yy[nextSym-1];
  1671.          unzftab[seqToUnseq[tmp]]++;
  1672.          if (smallMode)
  1673.             ll16[last] = seqToUnseq[tmp]; else
  1674.             ll8[last]  = seqToUnseq[tmp];
  1675.  
  1676.          /*--
  1677.             This loop is hammered during decompression,
  1678.             hence the unrolling.
  1679.  
  1680.             for (j = nextSym-1; j > 0; j--) yy[j] = yy[j-1];
  1681.          --*/
  1682.  
  1683.          j = nextSym-1;
  1684.          for (; j > 3; j -= 4) {
  1685.             yy[j]   = yy[j-1];
  1686.             yy[j-1] = yy[j-2];
  1687.             yy[j-2] = yy[j-3];
  1688.             yy[j-3] = yy[j-4];
  1689.          }
  1690.          for (; j > 0; j--) yy[j] = yy[j-1];
  1691.  
  1692.          yy[0] = tmp;
  1693.          GET_MTF_VAL(nextSym);
  1694.          continue;
  1695.       }
  1696.    }
  1697. }
  1698.  
  1699.  
  1700. /*---------------------------------------------------*/
  1701. /*--- Block-sorting machinery                     ---*/
  1702. /*---------------------------------------------------*/
  1703.  
  1704. /*---------------------------------------------*/
  1705. /*--
  1706.   Compare two strings in block.  We assume (see
  1707.   discussion above) that i1 and i2 have a max
  1708.   offset of 10 on entry, and that the first
  1709.   bytes of both block and quadrant have been
  1710.   copied into the "overshoot area", ie
  1711.   into the subscript range
  1712.   [last+1 .. last+NUM_OVERSHOOT_BYTES].
  1713. --*/
  1714. INLINE Bool fullGtU ( Int32 i1, Int32 i2 )
  1715. {
  1716.    Int32 k;
  1717.    UChar c1, c2;
  1718.    UInt16 s1, s2;
  1719.  
  1720.    #if DEBUG
  1721.       /*--
  1722.         shellsort shouldn't ask to compare
  1723.         something with itself.
  1724.       --*/
  1725.       assert (i1 != i2);
  1726.    #endif
  1727.  
  1728.    c1 = block[i1];
  1729.    c2 = block[i2];
  1730.    if (c1 != c2) return (c1 > c2);
  1731.    i1++; i2++;
  1732.  
  1733.    c1 = block[i1];
  1734.    c2 = block[i2];
  1735.    if (c1 != c2) return (c1 > c2);
  1736.    i1++; i2++;
  1737.  
  1738.    c1 = block[i1];
  1739.    c2 = block[i2];
  1740.    if (c1 != c2) return (c1 > c2);
  1741.    i1++; i2++;
  1742.  
  1743.    c1 = block[i1];
  1744.    c2 = block[i2];
  1745.    if (c1 != c2) return (c1 > c2);
  1746.    i1++; i2++;
  1747.  
  1748.    c1 = block[i1];
  1749.    c2 = block[i2];
  1750.    if (c1 != c2) return (c1 > c2);
  1751.    i1++; i2++;
  1752.  
  1753.    c1 = block[i1];
  1754.    c2 = block[i2];
  1755.    if (c1 != c2) return (c1 > c2);
  1756.    i1++; i2++;
  1757.  
  1758.    k = last + 1;
  1759.  
  1760.    do {
  1761.  
  1762.       c1 = block[i1];
  1763.       c2 = block[i2];
  1764.       if (c1 != c2) return (c1 > c2);
  1765.       s1 = quadrant[i1];
  1766.       s2 = quadrant[i2];
  1767.       if (s1 != s2) return (s1 > s2);
  1768.       i1++; i2++;
  1769.  
  1770.       c1 = block[i1];
  1771.       c2 = block[i2];
  1772.       if (c1 != c2) return (c1 > c2);
  1773.       s1 = quadrant[i1];
  1774.       s2 = quadrant[i2];
  1775.       if (s1 != s2) return (s1 > s2);
  1776.       i1++; i2++;
  1777.  
  1778.       c1 = block[i1];
  1779.       c2 = block[i2];
  1780.       if (c1 != c2) return (c1 > c2);
  1781.       s1 = quadrant[i1];
  1782.       s2 = quadrant[i2];
  1783.       if (s1 != s2) return (s1 > s2);
  1784.       i1++; i2++;
  1785.  
  1786.       c1 = block[i1];
  1787.       c2 = block[i2];
  1788.       if (c1 != c2) return (c1 > c2);
  1789.       s1 = quadrant[i1];
  1790.       s2 = quadrant[i2];
  1791.       if (s1 != s2) return (s1 > s2);
  1792.       i1++; i2++;
  1793.  
  1794.       if (i1 > last) { i1 -= last; i1--; };
  1795.       if (i2 > last) { i2 -= last; i2--; };
  1796.  
  1797.       k -= 4;
  1798.       workDone++;
  1799.    }
  1800.       while (k >= 0);
  1801.  
  1802.    return False;
  1803. }
  1804.  
  1805. /*---------------------------------------------*/
  1806. /*--
  1807.    Knuth's increments seem to work better
  1808.    than Incerpi-Sedgewick here.  Possibly
  1809.    because the number of elems to sort is
  1810.    usually small, typically <= 20.
  1811. --*/
  1812. Int32 incs[14] = { 1, 4, 13, 40, 121, 364, 1093, 3280,
  1813.                    9841, 29524, 88573, 265720,
  1814.                    797161, 2391484 };
  1815.  
  1816. void simpleSort ( Int32 lo, Int32 hi, Int32 d )
  1817. {
  1818.    Int32 i, j, h, bigN, hp;
  1819.    Int32 v;
  1820.  
  1821.    bigN = hi - lo + 1;
  1822.    if (bigN < 2) return;
  1823.  
  1824.    hp = 0;
  1825.    while (incs[hp] < bigN) hp++;
  1826.    hp--;
  1827.  
  1828.    for (; hp >= 0; hp--) {
  1829.       h = incs[hp];
  1830.       if (verbosity >= 5)
  1831.          fprintf ( stderr, "          shell increment %d\n", h );
  1832.  
  1833.       i = lo + h;
  1834.       while (True) {
  1835.  
  1836.          /*-- copy 1 --*/
  1837.          if (i > hi) break;
  1838.          v = zptr[i];
  1839.          j = i;
  1840.          while ( fullGtU ( zptr[j-h]+d, v+d ) ) {
  1841.             zptr[j] = zptr[j-h];
  1842.             j = j - h;
  1843.             if (j <= (lo + h - 1)) break;
  1844.          }
  1845.          zptr[j] = v;
  1846.          i++;
  1847.  
  1848.          /*-- copy 2 --*/
  1849.          if (i > hi) break;
  1850.          v = zptr[i];
  1851.          j = i;
  1852.          while ( fullGtU ( zptr[j-h]+d, v+d ) ) {
  1853.             zptr[j] = zptr[j-h];
  1854.             j = j - h;
  1855.             if (j <= (lo + h - 1)) break;
  1856.          }
  1857.          zptr[j] = v;
  1858.          i++;
  1859.  
  1860.          /*-- copy 3 --*/
  1861.          if (i > hi) break;
  1862.          v = zptr[i];
  1863.          j = i;
  1864.          while ( fullGtU ( zptr[j-h]+d, v+d ) ) {
  1865.             zptr[j] = zptr[j-h];
  1866.             j = j - h;
  1867.             if (j <= (lo + h - 1)) break;
  1868.          }
  1869.          zptr[j] = v;
  1870.          i++;
  1871.  
  1872.          if (workDone > workLimit && firstAttempt) return;
  1873.       }
  1874.    }
  1875. }
  1876.  
  1877.  
  1878. /*---------------------------------------------*/
  1879. /*--
  1880.    The following is an implementation of
  1881.    an elegant 3-way quicksort for strings,
  1882.    described in a paper "Fast Algorithms for
  1883.    Sorting and Searching Strings", by Robert
  1884.    Sedgewick and Jon L. Bentley.
  1885. --*/
  1886.  
  1887. #define swap(lv1, lv2) \
  1888.    { Int32 tmp = lv1; lv1 = lv2; lv2 = tmp; }
  1889.  
  1890. INLINE void vswap ( Int32 p1, Int32 p2, Int32 n )
  1891. {
  1892.    while (n > 0) {
  1893.       swap(zptr[p1], zptr[p2]);
  1894.       p1++; p2++; n--;
  1895.    }
  1896. }
  1897.  
  1898. INLINE UChar med3 ( UChar a, UChar b, UChar c )
  1899. {
  1900.    UChar t;
  1901.    if (a > b) { t = a; a = b; b = t; };
  1902.    if (b > c) { t = b; b = c; c = t; };
  1903.    if (a > b)          b = a;
  1904.    return b;
  1905. }
  1906.  
  1907.  
  1908. #define min(a,b) ((a) < (b)) ? (a) : (b)
  1909.  
  1910. typedef
  1911.    struct { Int32 ll; Int32 hh; Int32 dd; }
  1912.    StackElem;
  1913.  
  1914. #define push(lz,hz,dz) { stack[sp].ll = lz; \
  1915.                          stack[sp].hh = hz; \
  1916.                          stack[sp].dd = dz; \
  1917.                          sp++; }
  1918.  
  1919. #define pop(lz,hz,dz) { sp--;               \
  1920.                         lz = stack[sp].ll;  \
  1921.                         hz = stack[sp].hh;  \
  1922.                         dz = stack[sp].dd; }
  1923.  
  1924. #define SMALL_THRESH 20
  1925. #define DEPTH_THRESH 10
  1926.  
  1927. /*--
  1928.    If you are ever unlucky/improbable enough
  1929.    to get a stack overflow whilst sorting,
  1930.    increase the following constant and try
  1931.    again.  In practice I have never seen the
  1932.    stack go above 27 elems, so the following
  1933.    limit seems very generous.
  1934. --*/
  1935. #define QSORT_STACK_SIZE 1000
  1936.  
  1937.  
  1938. void qSort3 ( Int32 loSt, Int32 hiSt, Int32 dSt )
  1939. {
  1940.    Int32 unLo, unHi, ltLo, gtHi, med, n, m;
  1941.    Int32 sp, lo, hi, d;
  1942.    StackElem stack[QSORT_STACK_SIZE];
  1943.  
  1944.    sp = 0;
  1945.    push ( loSt, hiSt, dSt );
  1946.  
  1947.    while (sp > 0) {
  1948.  
  1949.       if (sp >= QSORT_STACK_SIZE) panic ( "stack overflow in qSort3" );
  1950.  
  1951.       pop ( lo, hi, d );
  1952.  
  1953.       if (hi - lo < SMALL_THRESH || d > DEPTH_THRESH) {
  1954.          simpleSort ( lo, hi, d );
  1955.          if (workDone > workLimit && firstAttempt) return;
  1956.          continue;
  1957.       }
  1958.  
  1959.       med = med3 ( block[zptr[ lo         ]+d],
  1960.                    block[zptr[ hi         ]+d],
  1961.                    block[zptr[ (lo+hi)>>1 ]+d] );
  1962.  
  1963.       unLo = ltLo = lo;
  1964.       unHi = gtHi = hi;
  1965.  
  1966.       while (True) {
  1967.          while (True) {
  1968.             if (unLo > unHi) break;
  1969.             n = ((Int32)block[zptr[unLo]+d]) - med;
  1970.             if (n == 0) { swap(zptr[unLo], zptr[ltLo]); ltLo++; unLo++; continue; };
  1971.             if (n >  0) break;
  1972.             unLo++;
  1973.          }
  1974.          while (True) {
  1975.             if (unLo > unHi) break;
  1976.             n = ((Int32)block[zptr[unHi]+d]) - med;
  1977.             if (n == 0) { swap(zptr[unHi], zptr[gtHi]); gtHi--; unHi--; continue; };
  1978.             if (n <  0) break;
  1979.             unHi--;
  1980.          }
  1981.          if (unLo > unHi) break;
  1982.          swap(zptr[unLo], zptr[unHi]); unLo++; unHi--;
  1983.       }
  1984.       #if DEBUG
  1985.          assert (unHi == unLo-1);
  1986.       #endif
  1987.  
  1988.       if (gtHi < ltLo) {
  1989.          push(lo, hi, d+1 );
  1990.          continue;
  1991.       }
  1992.  
  1993.       n = min(ltLo-lo, unLo-ltLo); vswap(lo, unLo-n, n);
  1994.       m = min(hi-gtHi, gtHi-unHi); vswap(unLo, hi-m+1, m);
  1995.  
  1996.       n = lo + unLo - ltLo - 1;
  1997.       m = hi - (gtHi - unHi) + 1;
  1998.  
  1999.       push ( lo, n, d );
  2000.       push ( n+1, m-1, d+1 );
  2001.       push ( m, hi, d );
  2002.    }
  2003. }
  2004.  
  2005.  
  2006. /*---------------------------------------------*/
  2007.  
  2008. #define BIGFREQ(b) (ftab[((b)+1) << 8] - ftab[(b) << 8])
  2009.  
  2010. #define SETMASK (1 << 21)
  2011. #define CLEARMASK (~(SETMASK))
  2012.  
  2013. void sortIt ( void )
  2014. {
  2015.    Int32 i, j, ss, sb;
  2016.    Int32 runningOrder[256];
  2017.    Int32 copy[256];
  2018.    Bool bigDone[256];
  2019.    UChar c1, c2;
  2020.    Int32 numQSorted;
  2021.  
  2022.    /*--
  2023.       In the various block-sized structures, live data runs
  2024.       from 0 to last+NUM_OVERSHOOT_BYTES inclusive.  First,
  2025.       set up the overshoot area for block.
  2026.    --*/
  2027.  
  2028.    if (verbosity >= 4) fprintf ( stderr, "        sort initialise ...\n" );
  2029.    for (i = 0; i < NUM_OVERSHOOT_BYTES; i++)
  2030.        block[last+i+1] = block[i % (last+1)];
  2031.    for (i = 0; i <= last+NUM_OVERSHOOT_BYTES; i++)
  2032.        quadrant[i] = 0;
  2033.  
  2034.    block[-1] = block[last];
  2035.  
  2036.    if (last < 4000) {
  2037.  
  2038.       /*--
  2039.          Use simpleSort(), since the full sorting mechanism
  2040.          has quite a large constant overhead.
  2041.       --*/
  2042.       if (verbosity >= 4) fprintf ( stderr, "        simpleSort ...\n" );
  2043.       for (i = 0; i <= last; i++) zptr[i] = i;
  2044.       firstAttempt = False;
  2045.       workDone = workLimit = 0;
  2046.       simpleSort ( 0, last, 0 );
  2047.       if (verbosity >= 4) fprintf ( stderr, "        simpleSort done.\n" );
  2048.  
  2049.    } else {
  2050.  
  2051.       numQSorted = 0;
  2052.       for (i = 0; i <= 255; i++) bigDone[i] = False;
  2053.  
  2054.       if (verbosity >= 4) fprintf ( stderr, "        bucket sorting ...\n" );
  2055.  
  2056.       for (i = 0; i <= 65536; i++) ftab[i] = 0;
  2057.  
  2058.       c1 = block[-1];
  2059.       for (i = 0; i <= last; i++) {
  2060.          c2 = block[i];
  2061.          ftab[(c1 << 8) + c2]++;
  2062.          c1 = c2;
  2063.       }
  2064.  
  2065.       for (i = 1; i <= 65536; i++) ftab[i] += ftab[i-1];
  2066.  
  2067.       c1 = block[0];
  2068.       for (i = 0; i < last; i++) {
  2069.          c2 = block[i+1];
  2070.          j = (c1 << 8) + c2;
  2071.          c1 = c2;
  2072.          ftab[j]--;
  2073.          zptr[ftab[j]] = i;
  2074.       }
  2075.       j = (block[last] << 8) + block[0];
  2076.       ftab[j]--;
  2077.       zptr[ftab[j]] = last;
  2078.  
  2079.       /*--
  2080.          Now ftab contains the first loc of every small bucket.
  2081.          Calculate the running order, from smallest to largest
  2082.          big bucket.
  2083.       --*/
  2084.  
  2085.       for (i = 0; i <= 255; i++) runningOrder[i] = i;
  2086.  
  2087.       {
  2088.          Int32 vv;
  2089.          Int32 h = 1;
  2090.          do h = 3 * h + 1; while (h <= 256);
  2091.          do {
  2092.             h = h / 3;
  2093.             for (i = h; i <= 255; i++) {
  2094.                vv = runningOrder[i];
  2095.                j = i;
  2096.                while ( BIGFREQ(runningOrder[j-h]) > BIGFREQ(vv) ) {
  2097.                   runningOrder[j] = runningOrder[j-h];
  2098.                   j = j - h;
  2099.                   if (j <= (h - 1)) goto zero;
  2100.                }
  2101.                zero:
  2102.                runningOrder[j] = vv;
  2103.             }
  2104.          } while (h != 1);
  2105.       }
  2106.  
  2107.       /*--
  2108.          The main sorting loop.
  2109.       --*/
  2110.  
  2111.       for (i = 0; i <= 255; i++) {
  2112.  
  2113.          /*--
  2114.             Process big buckets, starting with the least full.
  2115.          --*/
  2116.          ss = runningOrder[i];
  2117.  
  2118.          /*--
  2119.             Complete the big bucket [ss] by quicksorting
  2120.             any unsorted small buckets [ss, j].  Hopefully
  2121.             previous pointer-scanning phases have already
  2122.             completed many of the small buckets [ss, j], so
  2123.             we don't have to sort them at all.
  2124.          --*/
  2125.          for (j = 0; j <= 255; j++) {
  2126.             sb = (ss << 8) + j;
  2127.             if ( ! (ftab[sb] & SETMASK) ) {
  2128.                Int32 lo = ftab[sb]   & CLEARMASK;
  2129.                Int32 hi = (ftab[sb+1] & CLEARMASK) - 1;
  2130.                if (hi > lo) {
  2131.                   if (verbosity >= 4)
  2132.                      fprintf ( stderr,
  2133.                                "        qsort [0x%x, 0x%x]   done %d   this %d\n",
  2134.                                ss, j, numQSorted, hi - lo + 1 );
  2135.                   qSort3 ( lo, hi, 2 );
  2136.                   numQSorted += ( hi - lo + 1 );
  2137.                   if (workDone > workLimit && firstAttempt) return;
  2138.                }
  2139.                ftab[sb] |= SETMASK;
  2140.             }
  2141.          }
  2142.  
  2143.          /*--
  2144.             The ss big bucket is now done.  Record this fact,
  2145.             and update the quadrant descriptors.  Remember to
  2146.             update quadrants in the overshoot area too, if
  2147.             necessary.  The "if (i < 255)" test merely skips
  2148.             this updating for the last bucket processed, since
  2149.             updating for the last bucket is pointless.
  2150.          --*/
  2151.          bigDone[ss] = True;
  2152.  
  2153.          if (i < 255) {
  2154.             Int32 bbStart  = ftab[ss << 8] & CLEARMASK;
  2155.             Int32 bbSize   = (ftab[(ss+1) << 8] & CLEARMASK) - bbStart;
  2156.             Int32 shifts   = 0;
  2157.  
  2158.             while ((bbSize >> shifts) > 65534) shifts++;
  2159.  
  2160.             for (j = 0; j < bbSize; j++) {
  2161.                Int32 a2update     = zptr[bbStart + j];
  2162.                UInt16 qVal        = (UInt16)(j >> shifts);
  2163.                quadrant[a2update] = qVal;
  2164.                if (a2update < NUM_OVERSHOOT_BYTES)
  2165.                   quadrant[a2update + last + 1] = qVal;
  2166.             }
  2167.  
  2168.             if (! ( ((bbSize-1) >> shifts) <= 65535 )) panic ( "sortIt" );
  2169.          }
  2170.  
  2171.          /*--
  2172.             Now scan this big bucket so as to synthesise the
  2173.             sorted order for small buckets [t, ss] for all t != ss.
  2174.          --*/
  2175.          for (j = 0; j <= 255; j++)
  2176.             copy[j] = ftab[(j << 8) + ss] & CLEARMASK;
  2177.  
  2178.          for (j = ftab[ss << 8] & CLEARMASK;
  2179.               j < (ftab[(ss+1) << 8] & CLEARMASK);
  2180.               j++) {
  2181.             c1 = block[zptr[j]-1];
  2182.             if ( ! bigDone[c1] ) {
  2183.                zptr[copy[c1]] = zptr[j] == 0 ? last : zptr[j] - 1;
  2184.                copy[c1] ++;
  2185.             }
  2186.          }
  2187.  
  2188.          for (j = 0; j <= 255; j++) ftab[(j << 8) + ss] |= SETMASK;
  2189.       }
  2190.       if (verbosity >= 4)
  2191.          fprintf ( stderr, "        %d pointers, %d sorted, %d scanned\n",
  2192.                            last+1, numQSorted, (last+1) - numQSorted );
  2193.    }
  2194. }
  2195.  
  2196.  
  2197. /*---------------------------------------------------*/
  2198. /*--- Stuff for randomising repetitive blocks     ---*/
  2199. /*---------------------------------------------------*/
  2200.  
  2201. /*---------------------------------------------*/
  2202. Int32 rNums[512] = {
  2203.    619, 720, 127, 481, 931, 816, 813, 233, 566, 247,
  2204.    985, 724, 205, 454, 863, 491, 741, 242, 949, 214,
  2205.    733, 859, 335, 708, 621, 574, 73, 654, 730, 472,
  2206.    419, 436, 278, 496, 867, 210, 399, 680, 480, 51,
  2207.    878, 465, 811, 169, 869, 675, 611, 697, 867, 561,
  2208.    862, 687, 507, 283, 482, 129, 807, 591, 733, 623,
  2209.    150, 238, 59, 379, 684, 877, 625, 169, 643, 105,
  2210.    170, 607, 520, 932, 727, 476, 693, 425, 174, 647,
  2211.    73, 122, 335, 530, 442, 853, 695, 249, 445, 515,
  2212.    909, 545, 703, 919, 874, 474, 882, 500, 594, 612,
  2213.    641, 801, 220, 162, 819, 984, 589, 513, 495, 799,
  2214.    161, 604, 958, 533, 221, 400, 386, 867, 600, 782,
  2215.    382, 596, 414, 171, 516, 375, 682, 485, 911, 276,
  2216.    98, 553, 163, 354, 666, 933, 424, 341, 533, 870,
  2217.    227, 730, 475, 186, 263, 647, 537, 686, 600, 224,
  2218.    469, 68, 770, 919, 190, 373, 294, 822, 808, 206,
  2219.    184, 943, 795, 384, 383, 461, 404, 758, 839, 887,
  2220.    715, 67, 618, 276, 204, 918, 873, 777, 604, 560,
  2221.    951, 160, 578, 722, 79, 804, 96, 409, 713, 940,
  2222.    652, 934, 970, 447, 318, 353, 859, 672, 112, 785,
  2223.    645, 863, 803, 350, 139, 93, 354, 99, 820, 908,
  2224.    609, 772, 154, 274, 580, 184, 79, 626, 630, 742,
  2225.    653, 282, 762, 623, 680, 81, 927, 626, 789, 125,
  2226.    411, 521, 938, 300, 821, 78, 343, 175, 128, 250,
  2227.    170, 774, 972, 275, 999, 639, 495, 78, 352, 126,
  2228.    857, 956, 358, 619, 580, 124, 737, 594, 701, 612,
  2229.    669, 112, 134, 694, 363, 992, 809, 743, 168, 974,
  2230.    944, 375, 748, 52, 600, 747, 642, 182, 862, 81,
  2231.    344, 805, 988, 739, 511, 655, 814, 334, 249, 515,
  2232.    897, 955, 664, 981, 649, 113, 974, 459, 893, 228,
  2233.    433, 837, 553, 268, 926, 240, 102, 654, 459, 51,
  2234.    686, 754, 806, 760, 493, 403, 415, 394, 687, 700,
  2235.    946, 670, 656, 610, 738, 392, 760, 799, 887, 653,
  2236.    978, 321, 576, 617, 626, 502, 894, 679, 243, 440,
  2237.    680, 879, 194, 572, 640, 724, 926, 56, 204, 700,
  2238.    707, 151, 457, 449, 797, 195, 791, 558, 945, 679,
  2239.    297, 59, 87, 824, 713, 663, 412, 693, 342, 606,
  2240.    134, 108, 571, 364, 631, 212, 174, 643, 304, 329,
  2241.    343, 97, 430, 751, 497, 314, 983, 374, 822, 928,
  2242.    140, 206, 73, 263, 980, 736, 876, 478, 430, 305,
  2243.    170, 514, 364, 692, 829, 82, 855, 953, 676, 246,
  2244.    369, 970, 294, 750, 807, 827, 150, 790, 288, 923,
  2245.    804, 378, 215, 828, 592, 281, 565, 555, 710, 82,
  2246.    896, 831, 547, 261, 524, 462, 293, 465, 502, 56,
  2247.    661, 821, 976, 991, 658, 869, 905, 758, 745, 193,
  2248.    768, 550, 608, 933, 378, 286, 215, 979, 792, 961,
  2249.    61, 688, 793, 644, 986, 403, 106, 366, 905, 644,
  2250.    372, 567, 466, 434, 645, 210, 389, 550, 919, 135,
  2251.    780, 773, 635, 389, 707, 100, 626, 958, 165, 504,
  2252.    920, 176, 193, 713, 857, 265, 203, 50, 668, 108,
  2253.    645, 990, 626, 197, 510, 357, 358, 850, 858, 364,
  2254.    936, 638
  2255. };
  2256.  
  2257.  
  2258. #define RAND_DECLS                                \
  2259.    Int32 rNToGo = 0;                              \
  2260.    Int32 rTPos  = 0;                              \
  2261.  
  2262. #define RAND_MASK ((rNToGo == 1) ? 1 : 0)
  2263.  
  2264. #define RAND_UPD_MASK                             \
  2265.    if (rNToGo == 0) {                             \
  2266.       rNToGo = rNums[rTPos];                      \
  2267.       rTPos++; if (rTPos == 512) rTPos = 0;       \
  2268.    }                                              \
  2269.    rNToGo--;
  2270.  
  2271.  
  2272.  
  2273. /*---------------------------------------------------*/
  2274. /*--- The Reversible Transformation (tm)          ---*/
  2275. /*---------------------------------------------------*/
  2276.  
  2277. /*---------------------------------------------*/
  2278. void randomiseBlock ( void )
  2279. {
  2280.    Int32 i;
  2281.    RAND_DECLS;
  2282.    for (i = 0; i < 256; i++) inUse[i] = False;
  2283.  
  2284.    for (i = 0; i <= last; i++) {
  2285.       RAND_UPD_MASK;
  2286.       block[i] ^= RAND_MASK;
  2287.       inUse[block[i]] = True;
  2288.    }
  2289. }
  2290.  
  2291.  
  2292. /*---------------------------------------------*/
  2293. void doReversibleTransformation ( void )
  2294. {
  2295.    Int32 i;
  2296.  
  2297.    if (verbosity >= 2) fprintf ( stderr, "\n" );
  2298.  
  2299.    workLimit       = workFactor * last;
  2300.    workDone        = 0;
  2301.    blockRandomised = False;
  2302.    firstAttempt    = True;
  2303.  
  2304.    sortIt ();
  2305.  
  2306.    if (verbosity >= 3)
  2307.       fprintf ( stderr, "      %d work, %d block, ratio %5.2f\n",
  2308.                         workDone, last, (float)workDone / (float)(last) );
  2309.  
  2310.    if (workDone > workLimit && firstAttempt) {
  2311.       if (verbosity >= 2)
  2312.          fprintf ( stderr, "    sorting aborted; randomising block\n" );
  2313.       randomiseBlock ();
  2314.       workLimit = workDone = 0;
  2315.       blockRandomised = True;
  2316.       firstAttempt = False;
  2317.       sortIt();
  2318.       if (verbosity >= 3)
  2319.          fprintf ( stderr, "      %d work, %d block, ratio %f\n",
  2320.                            workDone, last, (float)workDone / (float)(last) );
  2321.    }
  2322.  
  2323.    origPtr = -1;
  2324.    for (i = 0; i <= last; i++)
  2325.        if (zptr[i] == 0)
  2326.           { origPtr = i; break; };
  2327.  
  2328.    if (origPtr == -1) panic ( "doReversibleTransformation" );
  2329. }
  2330.  
  2331.  
  2332. /*---------------------------------------------*/
  2333.  
  2334. INLINE Int32 indexIntoF ( Int32 indx, Int32 *cftab )
  2335. {
  2336.    Int32 nb, na, mid;
  2337.    nb = 0;
  2338.    na = 256;
  2339.    do {
  2340.       mid = (nb + na) >> 1;
  2341.       if (indx >= cftab[mid]) nb = mid; else na = mid;
  2342.    }
  2343.    while (na - nb != 1);
  2344.    return nb;
  2345. }
  2346.  
  2347.  
  2348. #define GET_SMALL(cccc)                     \
  2349.                                             \
  2350.       cccc = indexIntoF ( tPos, cftab );    \
  2351.       tPos = GET_LL(tPos);
  2352.  
  2353.  
  2354. void undoReversibleTransformation_small ( FILE* dst )
  2355. {
  2356.    Int32  cftab[257], cftabAlso[257];
  2357.    Int32  i, j, tmp, tPos;
  2358.    UChar  ch;
  2359.  
  2360.    /*--
  2361.       We assume here that the global array unzftab will
  2362.       already be holding the frequency counts for
  2363.       ll8[0 .. last].
  2364.    --*/
  2365.  
  2366.    /*-- Set up cftab to facilitate generation of indexIntoF --*/
  2367.    cftab[0] = 0;
  2368.    for (i = 1; i <= 256; i++) cftab[i] = unzftab[i-1];
  2369.    for (i = 1; i <= 256; i++) cftab[i] += cftab[i-1];
  2370.  
  2371.    /*-- Make a copy of it, used in generation of T --*/
  2372.    for (i = 0; i <= 256; i++) cftabAlso[i] = cftab[i];
  2373.  
  2374.    /*-- compute the T vector --*/
  2375.    for (i = 0; i <= last; i++) {
  2376.       ch = (UChar)ll16[i];
  2377.       SET_LL(i, cftabAlso[ch]);
  2378.       cftabAlso[ch]++;
  2379.    }
  2380.  
  2381.    /*--
  2382.       Compute T^(-1) by pointer reversal on T.  This is rather
  2383.       subtle, in that, if the original block was two or more
  2384.       (in general, N) concatenated copies of the same thing,
  2385.       the T vector will consist of N cycles, each of length
  2386.       blocksize / N, and decoding will involve traversing one
  2387.       of these cycles N times.  Which particular cycle doesn't
  2388.       matter -- they are all equivalent.  The tricky part is to
  2389.       make sure that the pointer reversal creates a correct
  2390.       reversed cycle for us to traverse.  So, the code below
  2391.       simply reverses whatever cycle origPtr happens to fall into,
  2392.       without regard to the cycle length.  That gives one reversed
  2393.       cycle, which for normal blocks, is the entire block-size long.
  2394.       For repeated blocks, it will be interspersed with the other
  2395.       N-1 non-reversed cycles.  Providing that the F-subscripting
  2396.       phase which follows starts at origPtr, all then works ok.
  2397.    --*/
  2398.    i = origPtr;
  2399.    j = GET_LL(i);
  2400.    do {
  2401.       tmp = GET_LL(j);
  2402.       SET_LL(j, i);
  2403.       i = j;
  2404.       j = tmp;
  2405.    }
  2406.       while (i != origPtr);
  2407.  
  2408.    /*--
  2409.       We recreate the original by subscripting F through T^(-1).
  2410.       The run-length-decoder below requires characters incrementally,
  2411.       so tPos is set to a starting value, and is updated by
  2412.       the GET_SMALL macro.
  2413.    --*/
  2414.    tPos   = origPtr;
  2415.  
  2416.    /*-------------------------------------------------*/
  2417.    /*--
  2418.       This is pretty much a verbatim copy of the
  2419.       run-length decoder present in the distribution
  2420.       bzip-0.21; it has to be here to avoid creating
  2421.       block[] as an intermediary structure.  As in 0.21,
  2422.       this code derives from some sent to me by
  2423.       Christian von Roques.
  2424.  
  2425.       It allows dst==NULL, so as to support the test (-t)
  2426.       option without slowing down the fast decompression
  2427.       code.
  2428.    --*/
  2429.    {
  2430.       IntNative retVal;
  2431.       Int32     i2, count, chPrev, ch2;
  2432.       UInt32    localCrc;
  2433.  
  2434.       count    = 0;
  2435.       i2       = 0;
  2436.       ch2      = 256;   /*-- not a char and not EOF --*/
  2437.       localCrc = getGlobalCRC();
  2438.  
  2439.       {
  2440.          RAND_DECLS;
  2441.          while ( i2 <= last ) {
  2442.             chPrev = ch2;
  2443.             GET_SMALL(ch2);
  2444.             if (blockRandomised) {
  2445.                RAND_UPD_MASK;
  2446.                ch2 ^= (UInt32)RAND_MASK;
  2447.             }
  2448.             i2++;
  2449.  
  2450.             if (dst)
  2451.                retVal = putc ( ch2, dst );
  2452.  
  2453.             UPDATE_CRC ( localCrc, (UChar)ch2 );
  2454.  
  2455.             if (ch2 != chPrev) {
  2456.                count = 1;
  2457.             } else {
  2458.                count++;
  2459.                if (count >= 4) {
  2460.                   Int32 j2;
  2461.                   UChar z;
  2462.                   GET_SMALL(z);
  2463.                   if (blockRandomised) {
  2464.                      RAND_UPD_MASK;
  2465.                      z ^= RAND_MASK;
  2466.                   }
  2467.                   for (j2 = 0;  j2 < (Int32)z;  j2++) {
  2468.                      if (dst) retVal = putc (ch2, dst);
  2469.                      UPDATE_CRC ( localCrc, (UChar)ch2 );
  2470.                   }
  2471.                   i2++;
  2472.                   count = 0;
  2473.                }
  2474.             }
  2475.          }
  2476.       }
  2477.  
  2478.       setGlobalCRC ( localCrc );
  2479.    }
  2480.    /*-- end of the in-line run-length-decoder. --*/
  2481. }
  2482. #undef GET_SMALL
  2483.  
  2484.  
  2485. /*---------------------------------------------*/
  2486.  
  2487. #define GET_FAST(cccc)                       \
  2488.                                              \
  2489.       cccc = ll8[tPos];                      \
  2490.       tPos = tt[tPos];
  2491.  
  2492.  
  2493. void undoReversibleTransformation_fast ( FILE* dst )
  2494. {
  2495.    Int32  cftab[257];
  2496.    Int32  i, tPos;
  2497.    UChar  ch;
  2498.  
  2499.    /*--
  2500.       We assume here that the global array unzftab will
  2501.       already be holding the frequency counts for
  2502.       ll8[0 .. last].
  2503.    --*/
  2504.  
  2505.    /*-- Set up cftab to facilitate generation of T^(-1) --*/
  2506.    cftab[0] = 0;
  2507.    for (i = 1; i <= 256; i++) cftab[i] = unzftab[i-1];
  2508.    for (i = 1; i <= 256; i++) cftab[i] += cftab[i-1];
  2509.  
  2510.    /*-- compute the T^(-1) vector --*/
  2511.    for (i = 0; i <= last; i++) {
  2512.       ch = (UChar)ll8[i];
  2513.       tt[cftab[ch]] = i;
  2514.       cftab[ch]++;
  2515.    }
  2516.  
  2517.    /*--
  2518.       We recreate the original by subscripting L through T^(-1).
  2519.       The run-length-decoder below requires characters incrementally,
  2520.       so tPos is set to a starting value, and is updated by
  2521.       the GET_FAST macro.
  2522.    --*/
  2523.    tPos   = tt[origPtr];
  2524.  
  2525.    /*-------------------------------------------------*/
  2526.    /*--
  2527.       This is pretty much a verbatim copy of the
  2528.       run-length decoder present in the distribution
  2529.       bzip-0.21; it has to be here to avoid creating
  2530.       block[] as an intermediary structure.  As in 0.21,
  2531.       this code derives from some sent to me by
  2532.       Christian von Roques.
  2533.    --*/
  2534.    {
  2535.       IntNative retVal;
  2536.       Int32     i2, count, chPrev, ch2;
  2537.       UInt32    localCrc;
  2538.  
  2539.       count    = 0;
  2540.       i2       = 0;
  2541.       ch2      = 256;   /*-- not a char and not EOF --*/
  2542.       localCrc = getGlobalCRC();
  2543.  
  2544.       if (blockRandomised) {
  2545.          RAND_DECLS;
  2546.          while ( i2 <= last ) {
  2547.             chPrev = ch2;
  2548.             GET_FAST(ch2);
  2549.             RAND_UPD_MASK;
  2550.             ch2 ^= (UInt32)RAND_MASK;
  2551.             i2++;
  2552.  
  2553.             retVal = putc ( ch2, dst );
  2554.             UPDATE_CRC ( localCrc, (UChar)ch2 );
  2555.  
  2556.             if (ch2 != chPrev) {
  2557.                count = 1;
  2558.             } else {
  2559.                count++;
  2560.                if (count >= 4) {
  2561.                   Int32 j2;
  2562.                   UChar z;
  2563.                   GET_FAST(z);
  2564.                   RAND_UPD_MASK;
  2565.                   z ^= RAND_MASK;
  2566.                   for (j2 = 0;  j2 < (Int32)z;  j2++) {
  2567.                      retVal = putc (ch2, dst);
  2568.                      UPDATE_CRC ( localCrc, (UChar)ch2 );
  2569.                   }
  2570.                   i2++;
  2571.                   count = 0;
  2572.                }
  2573.             }
  2574.          }
  2575.  
  2576.       } else {
  2577.  
  2578.          while ( i2 <= last ) {
  2579.             chPrev = ch2;
  2580.             GET_FAST(ch2);
  2581.             i2++;
  2582.  
  2583.             retVal = putc ( ch2, dst );
  2584.             UPDATE_CRC ( localCrc, (UChar)ch2 );
  2585.  
  2586.             if (ch2 != chPrev) {
  2587.                count = 1;
  2588.             } else {
  2589.                count++;
  2590.                if (count >= 4) {
  2591.                   Int32 j2;
  2592.                   UChar z;
  2593.                   GET_FAST(z);
  2594.                   for (j2 = 0;  j2 < (Int32)z;  j2++) {
  2595.                      retVal = putc (ch2, dst);
  2596.                      UPDATE_CRC ( localCrc, (UChar)ch2 );
  2597.                   }
  2598.                   i2++;
  2599.                   count = 0;
  2600.                }
  2601.             }
  2602.          }
  2603.  
  2604.       }   /*-- if (blockRandomised) --*/
  2605.  
  2606.       setGlobalCRC ( localCrc );
  2607.    }
  2608.    /*-- end of the in-line run-length-decoder. --*/
  2609. }
  2610. #undef GET_FAST
  2611.  
  2612.  
  2613. /*---------------------------------------------------*/
  2614. /*--- The block loader and RLEr                   ---*/
  2615. /*---------------------------------------------------*/
  2616.  
  2617. /*---------------------------------------------*/
  2618. /*  Top 16:   run length, 1 to 255.
  2619. *   Lower 16: the char, or MY_EOF for EOF.
  2620. */
  2621.  
  2622. #define MY_EOF 257
  2623.  
  2624. INLINE Int32 getRLEpair ( FILE* src )
  2625. {
  2626.    Int32     runLength;
  2627.    IntNative ch, chLatest;
  2628.  
  2629.    ch = getc ( src );
  2630.  
  2631.    /*--- Because I have no idea what kind of a value EOF is. ---*/
  2632.    if (ch == EOF) {
  2633.       ERROR_IF_NOT_ZERO ( ferror(src));
  2634.       return (1 << 16) | MY_EOF;
  2635.    }
  2636.  
  2637.    runLength = 0;
  2638.    do {
  2639.       chLatest = getc ( src );
  2640.       runLength++;
  2641.       bytesIn++;
  2642.    }
  2643.       while (ch == chLatest && runLength < 255);
  2644.  
  2645.    if ( chLatest != EOF ) {
  2646.       if ( ungetc ( chLatest, src ) == EOF )
  2647.          panic ( "getRLEpair: ungetc failed" );
  2648.    } else {
  2649.       ERROR_IF_NOT_ZERO ( ferror(src) );
  2650.    }
  2651.  
  2652.    /*--- Conditional is just a speedup hack. ---*/
  2653.    if (runLength == 1) {
  2654.       UPDATE_CRC ( globalCrc, (UChar)ch );
  2655.       return (1 << 16) | ch;
  2656.    } else {
  2657.       Int32 i;
  2658.       for (i = 1; i <= runLength; i++)
  2659.          UPDATE_CRC ( globalCrc, (UChar)ch );
  2660.       return (runLength << 16) | ch;
  2661.    }
  2662. }
  2663.  
  2664.  
  2665. /*---------------------------------------------*/
  2666. void loadAndRLEsource ( FILE* src )
  2667. {
  2668.    Int32 ch, allowableBlockSize, i;
  2669.  
  2670.    last = -1;
  2671.    ch   = 0;
  2672.  
  2673.    for (i = 0; i < 256; i++) inUse[i] = False;
  2674.  
  2675.    /*--- 20 is just a paranoia constant ---*/
  2676.    allowableBlockSize = 100000 * blockSize100k - 20;
  2677.  
  2678.    while (last < allowableBlockSize && ch != MY_EOF) {
  2679.       Int32 rlePair, runLen;
  2680.       rlePair = getRLEpair ( src );
  2681.       ch      = rlePair & 0xFFFF;
  2682.       runLen  = (UInt32)rlePair >> 16;
  2683.  
  2684.       #if DEBUG
  2685.          assert (runLen >= 1 && runLen <= 255);
  2686.       #endif
  2687.  
  2688.       if (ch != MY_EOF) {
  2689.          inUse[ch] = True;
  2690.          switch (runLen) {
  2691.             case 1:
  2692.                last++; block[last] = (UChar)ch; break;
  2693.             case 2:
  2694.                last++; block[last] = (UChar)ch;
  2695.                last++; block[last] = (UChar)ch; break;
  2696.             case 3:
  2697.                last++; block[last] = (UChar)ch;
  2698.                last++; block[last] = (UChar)ch;
  2699.                last++; block[last] = (UChar)ch; break;
  2700.             default:
  2701.                inUse[runLen-4] = True;
  2702.                last++; block[last] = (UChar)ch;
  2703.                last++; block[last] = (UChar)ch;
  2704.                last++; block[last] = (UChar)ch;
  2705.                last++; block[last] = (UChar)ch;
  2706.                last++; block[last] = (UChar)(runLen-4); break;
  2707.          }
  2708.       }
  2709.    }
  2710. }
  2711.  
  2712.  
  2713. /*---------------------------------------------------*/
  2714. /*--- Processing of complete files and streams    ---*/
  2715. /*---------------------------------------------------*/
  2716.  
  2717. /*---------------------------------------------*/
  2718. void compressStream ( FILE *stream, FILE *zStream )
  2719. {
  2720.    IntNative  retVal;
  2721.    UInt32     blockCRC, combinedCRC;
  2722.    Int32      blockNo;
  2723.  
  2724.    blockNo  = 0;
  2725.    bytesIn  = 0;
  2726.    bytesOut = 0;
  2727.    nBlocksRandomised = 0;
  2728.  
  2729.    SET_BINARY_MODE(stream);
  2730.    SET_BINARY_MODE(zStream);
  2731.  
  2732.    ERROR_IF_NOT_ZERO ( ferror(stream) );
  2733.    ERROR_IF_NOT_ZERO ( ferror(zStream) );
  2734.  
  2735.    bsSetStream ( zStream, True );
  2736.  
  2737.    /*--- Write `magic' bytes B and Z,
  2738.          then h indicating file-format == huffmanised,
  2739.          followed by a digit indicating blockSize100k.
  2740.    ---*/
  2741.    bsPutUChar ( 'B' );
  2742.    bsPutUChar ( 'Z' );
  2743.    bsPutUChar ( 'h' );
  2744.    bsPutUChar ( '0' + blockSize100k );
  2745.  
  2746.    combinedCRC = 0;
  2747.  
  2748.    if (verbosity >= 2) fprintf ( stderr, "\n" );
  2749.  
  2750.    while (True) {
  2751.  
  2752.       blockNo++;
  2753.       initialiseCRC ();
  2754.       loadAndRLEsource ( stream );
  2755.       ERROR_IF_NOT_ZERO ( ferror(stream) );
  2756.       if (last == -1) break;
  2757.  
  2758.       blockCRC = getFinalCRC ();
  2759.       combinedCRC = (combinedCRC << 1) | (combinedCRC >> 31);
  2760.       combinedCRC ^= blockCRC;
  2761.  
  2762.       if (verbosity >= 2)
  2763.          fprintf ( stderr, "    block %d: crc = 0x%8x, combined CRC = 0x%8x, size = %d",
  2764.                            blockNo, blockCRC, combinedCRC, last+1 );
  2765.  
  2766.       /*-- sort the block and establish posn of original string --*/
  2767.       doReversibleTransformation ();
  2768.  
  2769.       /*--
  2770.         A 6-byte block header, the value chosen arbitrarily
  2771.         as 0x314159265359 :-).  A 32 bit value does not really
  2772.         give a strong enough guarantee that the value will not
  2773.         appear by chance in the compressed datastream.  Worst-case
  2774.         probability of this event, for a 900k block, is about
  2775.         2.0e-3 for 32 bits, 1.0e-5 for 40 bits and 4.0e-8 for 48 bits.
  2776.         For a compressed file of size 100Gb -- about 100000 blocks --
  2777.         only a 48-bit marker will do.  NB: normal compression/
  2778.         decompression do *not* rely on these statistical properties.
  2779.         They are only important when trying to recover blocks from
  2780.         damaged files.
  2781.       --*/
  2782.       bsPutUChar ( 0x31 ); bsPutUChar ( 0x41 );
  2783.       bsPutUChar ( 0x59 ); bsPutUChar ( 0x26 );
  2784.       bsPutUChar ( 0x53 ); bsPutUChar ( 0x59 );
  2785.  
  2786.       /*-- Now the block's CRC, so it is in a known place. --*/
  2787.       bsPutUInt32 ( blockCRC );
  2788.  
  2789.       /*-- Now a single bit indicating randomisation. --*/
  2790.       if (blockRandomised) {
  2791.          bsW(1,1); nBlocksRandomised++;
  2792.       } else
  2793.          bsW(1,0);
  2794.  
  2795.       /*-- Finally, block's contents proper. --*/
  2796.       moveToFrontCodeAndSend ();
  2797.  
  2798.       ERROR_IF_NOT_ZERO ( ferror(zStream) );
  2799.    }
  2800.  
  2801.    if (verbosity >= 2 && nBlocksRandomised > 0)
  2802.       fprintf ( stderr, "    %d block%s needed randomisation\n",
  2803.                         nBlocksRandomised,
  2804.                         nBlocksRandomised == 1 ? "" : "s" );
  2805.  
  2806.    /*--
  2807.       Now another magic 48-bit number, 0x177245385090, to
  2808.       indicate the end of the last block.  (sqrt(pi), if
  2809.       you want to know.  I did want to use e, but it contains
  2810.       too much repetition -- 27 18 28 18 28 46 -- for me
  2811.       to feel statistically comfortable.  Call me paranoid.)
  2812.    --*/
  2813.  
  2814.    bsPutUChar ( 0x17 ); bsPutUChar ( 0x72 );
  2815.    bsPutUChar ( 0x45 ); bsPutUChar ( 0x38 );
  2816.    bsPutUChar ( 0x50 ); bsPutUChar ( 0x90 );
  2817.  
  2818.    bsPutUInt32 ( combinedCRC );
  2819.    if (verbosity >= 2)
  2820.       fprintf ( stderr, "    final combined CRC = 0x%x\n   ", combinedCRC );
  2821.  
  2822.    /*-- Close the files in an utterly paranoid way. --*/
  2823.    bsFinishedWithStream ();
  2824.  
  2825.    ERROR_IF_NOT_ZERO ( ferror(zStream) );
  2826.    retVal = fflush ( zStream );
  2827.    ERROR_IF_EOF ( retVal );
  2828.    retVal = fclose ( zStream );
  2829.    ERROR_IF_EOF ( retVal );
  2830.  
  2831.    ERROR_IF_NOT_ZERO ( ferror(stream) );
  2832.    retVal = fclose ( stream );
  2833.    ERROR_IF_EOF ( retVal );
  2834.  
  2835.    if (bytesIn == 0) bytesIn = 1;
  2836.    if (bytesOut == 0) bytesOut = 1;
  2837.  
  2838.    if (verbosity >= 1)
  2839.       fprintf ( stderr, "%6.3f:1, %6.3f bits/byte, "
  2840.                         "%5.2f%% saved, %d in, %d out.\n",
  2841.                 (float)bytesIn / (float)bytesOut,
  2842.                 (8.0 * (float)bytesOut) / (float)bytesIn,
  2843.                 100.0 * (1.0 - (float)bytesOut / (float)bytesIn),
  2844.                 bytesIn,
  2845.                 bytesOut
  2846.               );
  2847. }
  2848.  
  2849.  
  2850. /*---------------------------------------------*/
  2851. Bool uncompressStream ( FILE *zStream, FILE *stream )
  2852. {
  2853.    UChar      magic1, magic2, magic3, magic4;
  2854.    UChar      magic5, magic6;
  2855.    UInt32     storedBlockCRC, storedCombinedCRC;
  2856.    UInt32     computedBlockCRC, computedCombinedCRC;
  2857.    Int32      currBlockNo;
  2858.    IntNative  retVal;
  2859.  
  2860.    SET_BINARY_MODE(stream);
  2861.    SET_BINARY_MODE(zStream);
  2862.  
  2863.    ERROR_IF_NOT_ZERO ( ferror(stream) );
  2864.    ERROR_IF_NOT_ZERO ( ferror(zStream) );
  2865.  
  2866.    bsSetStream ( zStream, False );
  2867.  
  2868.    /*--
  2869.       A bad magic number is `recoverable from';
  2870.       return with False so the caller skips the file.
  2871.    --*/
  2872.    magic1 = bsGetUChar ();
  2873.    magic2 = bsGetUChar ();
  2874.    magic3 = bsGetUChar ();
  2875.    magic4 = bsGetUChar ();
  2876.    if (magic1 != 'B' ||
  2877.        magic2 != 'Z' ||
  2878.        magic3 != 'h' ||
  2879.        magic4 < '1'  ||
  2880.        magic4 > '9') {
  2881.      bsFinishedWithStream();
  2882.      retVal = fclose ( stream );
  2883.      ERROR_IF_EOF ( retVal );
  2884.      return False;
  2885.    }
  2886.  
  2887.    setDecompressStructureSizes ( magic4 - '0' );
  2888.    computedCombinedCRC = 0;
  2889.  
  2890.    if (verbosity >= 2) fprintf ( stderr, "\n    " );
  2891.    currBlockNo = 0;
  2892.  
  2893.    while (True) {
  2894.       magic1 = bsGetUChar ();
  2895.       magic2 = bsGetUChar ();
  2896.       magic3 = bsGetUChar ();
  2897.       magic4 = bsGetUChar ();
  2898.       magic5 = bsGetUChar ();
  2899.       magic6 = bsGetUChar ();
  2900.       if (magic1 == 0x17 && magic2 == 0x72 &&
  2901.           magic3 == 0x45 && magic4 == 0x38 &&
  2902.           magic5 == 0x50 && magic6 == 0x90) break;
  2903.  
  2904.       if (magic1 != 0x31 || magic2 != 0x41 ||
  2905.           magic3 != 0x59 || magic4 != 0x26 ||
  2906.           magic5 != 0x53 || magic6 != 0x59) badBlockHeader();
  2907.  
  2908.       storedBlockCRC = bsGetUInt32 ();
  2909.  
  2910.       if (bsR(1) == 1)
  2911.          blockRandomised = True; else
  2912.          blockRandomised = False;
  2913.  
  2914.       currBlockNo++;
  2915.       if (verbosity >= 2)
  2916.          fprintf ( stderr, "[%d: huff+mtf ", currBlockNo );
  2917.       getAndMoveToFrontDecode ();
  2918.       ERROR_IF_NOT_ZERO ( ferror(zStream) );
  2919.  
  2920.       initialiseCRC();
  2921.       if (verbosity >= 2) fprintf ( stderr, "rt+rld" );
  2922.       if (smallMode)
  2923.          undoReversibleTransformation_small ( stream );
  2924.          else
  2925.          undoReversibleTransformation_fast  ( stream );
  2926.  
  2927.       ERROR_IF_NOT_ZERO ( ferror(stream) );
  2928.  
  2929.       computedBlockCRC = getFinalCRC();
  2930.       if (verbosity >= 3)
  2931.          fprintf ( stderr, " {0x%x, 0x%x}", storedBlockCRC, computedBlockCRC );
  2932.       if (verbosity >= 2) fprintf ( stderr, "] " );
  2933.  
  2934.       /*-- A bad CRC is considered a fatal error. --*/
  2935.       if (storedBlockCRC != computedBlockCRC)
  2936.          crcError ( storedBlockCRC, computedBlockCRC );
  2937.  
  2938.       computedCombinedCRC = (computedCombinedCRC << 1) | (computedCombinedCRC >> 31);
  2939.       computedCombinedCRC ^= computedBlockCRC;
  2940.    };
  2941.  
  2942.    if (verbosity >= 2) fprintf ( stderr, "\n    " );
  2943.  
  2944.    storedCombinedCRC  = bsGetUInt32 ();
  2945.    if (verbosity >= 2)
  2946.       fprintf ( stderr,
  2947.                 "combined CRCs: stored = 0x%x, computed = 0x%x\n    ",
  2948.                 storedCombinedCRC, computedCombinedCRC );
  2949.    if (storedCombinedCRC != computedCombinedCRC)
  2950.       crcError ( storedCombinedCRC, computedCombinedCRC );
  2951.  
  2952.  
  2953.    bsFinishedWithStream ();
  2954.    ERROR_IF_NOT_ZERO ( ferror(zStream) );
  2955.    retVal = fclose ( zStream );
  2956.    ERROR_IF_EOF ( retVal );
  2957.  
  2958.    ERROR_IF_NOT_ZERO ( ferror(stream) );
  2959.    retVal = fflush ( stream );
  2960.    ERROR_IF_NOT_ZERO ( retVal );
  2961.    if (stream != stdout) {
  2962.       retVal = fclose ( stream );
  2963.       ERROR_IF_EOF ( retVal );
  2964.    }
  2965.    return True;
  2966. }
  2967.  
  2968.  
  2969. /*---------------------------------------------*/
  2970. Bool testStream ( FILE *zStream )
  2971. {
  2972.    UChar      magic1, magic2, magic3, magic4;
  2973.    UChar      magic5, magic6;
  2974.    UInt32     storedBlockCRC, storedCombinedCRC;
  2975.    UInt32     computedBlockCRC, computedCombinedCRC;
  2976.    Int32      currBlockNo;
  2977.    IntNative  retVal;
  2978.  
  2979.    SET_BINARY_MODE(zStream);
  2980.    ERROR_IF_NOT_ZERO ( ferror(zStream) );
  2981.  
  2982.    bsSetStream ( zStream, False );
  2983.  
  2984.    magic1 = bsGetUChar ();
  2985.    magic2 = bsGetUChar ();
  2986.    magic3 = bsGetUChar ();
  2987.    magic4 = bsGetUChar ();
  2988.    if (magic1 != 'B' ||
  2989.        magic2 != 'Z' ||
  2990.        magic3 != 'h' ||
  2991.        magic4 < '1'  ||
  2992.        magic4 > '9') {
  2993.      bsFinishedWithStream();
  2994.      fclose ( zStream );
  2995.      fprintf ( stderr, "\n%s: bad magic number (ie, not created by bzip2)\n",
  2996.                        inName );
  2997.      return False;
  2998.    }
  2999.  
  3000.    smallMode = True;
  3001.    setDecompressStructureSizes ( magic4 - '0' );
  3002.    computedCombinedCRC = 0;
  3003.  
  3004.    if (verbosity >= 2) fprintf ( stderr, "\n" );
  3005.    currBlockNo = 0;
  3006.  
  3007.    while (True) {
  3008.       magic1 = bsGetUChar ();
  3009.       magic2 = bsGetUChar ();
  3010.       magic3 = bsGetUChar ();
  3011.       magic4 = bsGetUChar ();
  3012.       magic5 = bsGetUChar ();
  3013.       magic6 = bsGetUChar ();
  3014.       if (magic1 == 0x17 && magic2 == 0x72 &&
  3015.           magic3 == 0x45 && magic4 == 0x38 &&
  3016.           magic5 == 0x50 && magic6 == 0x90) break;
  3017.  
  3018.       currBlockNo++;
  3019.       if (magic1 != 0x31 || magic2 != 0x41 ||
  3020.           magic3 != 0x59 || magic4 != 0x26 ||
  3021.           magic5 != 0x53 || magic6 != 0x59) {
  3022.          bsFinishedWithStream();
  3023.          fclose ( zStream );
  3024.          fprintf ( stderr,
  3025.                    "\n%s, block %d: bad header (not == 0x314159265359)\n",
  3026.                    inName, currBlockNo );
  3027.          return False;
  3028.       }
  3029.       storedBlockCRC = bsGetUInt32 ();
  3030.  
  3031.       if (bsR(1) == 1)
  3032.          blockRandomised = True; else
  3033.          blockRandomised = False;
  3034.  
  3035.       if (verbosity >= 2)
  3036.          fprintf ( stderr, "    block [%d: huff+mtf ", currBlockNo );
  3037.       getAndMoveToFrontDecode ();
  3038.       ERROR_IF_NOT_ZERO ( ferror(zStream) );
  3039.  
  3040.       initialiseCRC();
  3041.       if (verbosity >= 2) fprintf ( stderr, "rt+rld" );
  3042.       undoReversibleTransformation_small ( NULL );
  3043.  
  3044.       computedBlockCRC = getFinalCRC();
  3045.       if (verbosity >= 3)
  3046.          fprintf ( stderr, " {0x%x, 0x%x}", storedBlockCRC, computedBlockCRC );
  3047.       if (verbosity >= 2) fprintf ( stderr, "] " );
  3048.  
  3049.       if (storedBlockCRC != computedBlockCRC) {
  3050.          bsFinishedWithStream();
  3051.          fclose ( zStream );
  3052.          fprintf ( stderr, "\n%s, block %d: computed CRC does not match stored one\n",
  3053.                            inName, currBlockNo );
  3054.          return False;
  3055.       }
  3056.  
  3057.       if (verbosity >= 2) fprintf ( stderr, "ok\n" );
  3058.       computedCombinedCRC = (computedCombinedCRC << 1) | (computedCombinedCRC >> 31);
  3059.       computedCombinedCRC ^= computedBlockCRC;
  3060.    };
  3061.  
  3062.    storedCombinedCRC  = bsGetUInt32 ();
  3063.    if (verbosity >= 2)
  3064.       fprintf ( stderr,
  3065.                 "    combined CRCs: stored = 0x%x, computed = 0x%x\n    ",
  3066.                 storedCombinedCRC, computedCombinedCRC );
  3067.    if (storedCombinedCRC != computedCombinedCRC) {
  3068.       bsFinishedWithStream();
  3069.       fclose ( zStream );
  3070.       fprintf ( stderr, "\n%s: computed CRC does not match stored one\n",
  3071.                         inName );
  3072.       return False;
  3073.    }
  3074.  
  3075.    bsFinishedWithStream ();
  3076.    ERROR_IF_NOT_ZERO ( ferror(zStream) );
  3077.    retVal = fclose ( zStream );
  3078.    ERROR_IF_EOF ( retVal );
  3079.    return True;
  3080. }
  3081.  
  3082.  
  3083.  
  3084. /*---------------------------------------------------*/
  3085. /*--- Error [non-] handling grunge                ---*/
  3086. /*---------------------------------------------------*/
  3087.  
  3088. /*---------------------------------------------*/
  3089. void cadvise ( void )
  3090. {
  3091.    fprintf (
  3092.       stderr,
  3093.       "\nIt is possible that the compressed file(s) have become corrupted.\n"
  3094.         "You can use the -tvv option to test integrity of such files.\n\n"
  3095.         "You can use the `bzip2recover' program to *attempt* to recover\n"
  3096.         "data from undamaged sections of corrupted files.\n\n"
  3097.     );
  3098. }
  3099.  
  3100.  
  3101. /*---------------------------------------------*/
  3102. void showFileNames ( void )
  3103. {
  3104.    fprintf (
  3105.       stderr,
  3106.       "\tInput file = %s, output file = %s\n",
  3107.       inName==NULL  ? "(null)" : inName,
  3108.       outName==NULL ? "(null)" : outName
  3109.    );
  3110. }
  3111.  
  3112.  
  3113. /*---------------------------------------------*/
  3114. void cleanUpAndFail ( Int32 ec )
  3115. {
  3116.    IntNative retVal;
  3117.  
  3118.    if ( srcMode == SM_F2F && opMode != OM_TEST ) {
  3119.       fprintf ( stderr, "%s: Deleting output file %s, if it exists.\n",
  3120.                 progName,
  3121.                 outName==NULL ? "(null)" : outName );
  3122.       if (outputHandleJustInCase != NULL)
  3123.          fclose ( outputHandleJustInCase );
  3124.       retVal = remove ( outName );
  3125.       if (retVal != 0)
  3126.          fprintf ( stderr,
  3127.                    "%s: WARNING: deletion of output file (apparently) failed.\n",
  3128.                    progName );
  3129.    }
  3130.    if (numFileNames > 0 && numFilesProcessed < numFileNames) {
  3131.       fprintf ( stderr,
  3132.                 "%s: WARNING: some files have not been processed:\n"
  3133.                 "\t%d specified on command line, %d not processed yet.\n\n",
  3134.                 progName, numFileNames,
  3135.                           numFileNames - numFilesProcessed );
  3136.    }
  3137.    exit ( ec );
  3138. }
  3139.  
  3140.  
  3141. /*---------------------------------------------*/
  3142. void panic ( Char* s )
  3143. {
  3144.    fprintf ( stderr,
  3145.              "\n%s: PANIC -- internal consistency error:\n"
  3146.              "\t%s\n"
  3147.              "\tThis is a BUG.  Please report it to me at:\n"
  3148.              "\tjseward@acm.org\n",
  3149.              progName, s );
  3150.    showFileNames();
  3151.    cleanUpAndFail( 3 );
  3152. }
  3153.  
  3154.  
  3155. /*---------------------------------------------*/
  3156. void badBGLengths ( void )
  3157. {
  3158.    fprintf ( stderr,
  3159.              "\n%s: error when reading background model code lengths,\n"
  3160.              "\twhich probably means the compressed file is corrupted.\n",
  3161.              progName );
  3162.    showFileNames();
  3163.    cadvise();
  3164.    cleanUpAndFail( 2 );
  3165. }
  3166.  
  3167.  
  3168. /*---------------------------------------------*/
  3169. void crcError ( UInt32 crcStored, UInt32 crcComputed )
  3170. {
  3171.    fprintf ( stderr,
  3172.              "\n%s: Data integrity error when decompressing.\n"
  3173.              "\tStored CRC = 0x%x, computed CRC = 0x%x\n",
  3174.              progName, crcStored, crcComputed );
  3175.    showFileNames();
  3176.    cadvise();
  3177.    cleanUpAndFail( 2 );
  3178. }
  3179.  
  3180.  
  3181. /*---------------------------------------------*/
  3182. void compressedStreamEOF ( void )
  3183. {
  3184.    fprintf ( stderr,
  3185.              "\n%s: Compressed file ends unexpectedly;\n\t"
  3186.              "perhaps it is corrupted?  *Possible* reason follows.\n",
  3187.              progName );
  3188.    perror ( progName );
  3189.    showFileNames();
  3190.    cadvise();
  3191.    cleanUpAndFail( 2 );
  3192. }
  3193.  
  3194.  
  3195. /*---------------------------------------------*/
  3196. void ioError ( )
  3197. {
  3198.    fprintf ( stderr,
  3199.              "\n%s: I/O or other error, bailing out.  Possible reason follows.\n",
  3200.              progName );
  3201.    perror ( progName );
  3202.    showFileNames();
  3203.    cleanUpAndFail( 1 );
  3204. }
  3205.  
  3206.  
  3207. /*---------------------------------------------*/
  3208. void blockOverrun ()
  3209. {
  3210.    fprintf ( stderr,
  3211.              "\n%s: block overrun during decompression,\n"
  3212.              "\twhich probably means the compressed file\n"
  3213.              "\tis corrupted.\n",
  3214.              progName );
  3215.    showFileNames();
  3216.    cadvise();
  3217.    cleanUpAndFail( 2 );
  3218. }
  3219.  
  3220.  
  3221. /*---------------------------------------------*/
  3222. void badBlockHeader ()
  3223. {
  3224.    fprintf ( stderr,
  3225.              "\n%s: bad block header in the compressed file,\n"
  3226.              "\twhich probably means it is corrupted.\n",
  3227.              progName );
  3228.    showFileNames();
  3229.    cadvise();
  3230.    cleanUpAndFail( 2 );
  3231. }
  3232.  
  3233.  
  3234. /*---------------------------------------------*/
  3235. void bitStreamEOF ()
  3236. {
  3237.    fprintf ( stderr,
  3238.              "\n%s: read past the end of compressed data,\n"
  3239.              "\twhich probably means it is corrupted.\n",
  3240.              progName );
  3241.    showFileNames();
  3242.    cadvise();
  3243.    cleanUpAndFail( 2 );
  3244. }
  3245.  
  3246.  
  3247. /*---------------------------------------------*/
  3248. void mySignalCatcher ( IntNative n )
  3249. {
  3250.    fprintf ( stderr,
  3251.              "\n%s: Control-C (or similar) caught, quitting.\n",
  3252.              progName );
  3253.    cleanUpAndFail(1);
  3254. }
  3255.  
  3256.  
  3257. /*---------------------------------------------*/
  3258. void mySIGSEGVorSIGBUScatcher ( IntNative n )
  3259. {
  3260.    if (opMode == OM_Z)
  3261.       fprintf ( stderr,
  3262.                 "\n%s: Caught a SIGSEGV or SIGBUS whilst compressing,\n"
  3263.                 "\twhich probably indicates a bug in bzip2.  Please\n"
  3264.                 "\treport it to me at: jseward@acm.org\n",
  3265.                 progName );
  3266.       else
  3267.       fprintf ( stderr,
  3268.                 "\n%s: Caught a SIGSEGV or SIGBUS whilst decompressing,\n"
  3269.                 "\twhich probably indicates that the compressed data\n"
  3270.                 "\tis corrupted.\n",
  3271.                 progName );
  3272.  
  3273.    showFileNames();
  3274.    if (opMode == OM_Z)
  3275.       cleanUpAndFail( 3 ); else
  3276.       { cadvise(); cleanUpAndFail( 2 ); }
  3277. }
  3278.  
  3279.  
  3280. /*---------------------------------------------*/
  3281. void uncompressOutOfMemory ( Int32 draw, Int32 blockSize )
  3282. {
  3283.    fprintf ( stderr,
  3284.              "\n%s: Can't allocate enough memory for decompression.\n"
  3285.              "\tRequested %d bytes for a block size of %d.\n"
  3286.              "\tTry selecting space-economic decompress (with flag -s)\n"
  3287.              "\tand failing that, find a machine with more memory.\n",
  3288.              progName, draw, blockSize );
  3289.    showFileNames();
  3290.    cleanUpAndFail(1);
  3291. }
  3292.  
  3293.  
  3294. /*---------------------------------------------*/
  3295. void compressOutOfMemory ( Int32 draw, Int32 blockSize )
  3296. {
  3297.    fprintf ( stderr,
  3298.              "\n%s: Can't allocate enough memory for compression.\n"
  3299.              "\tRequested %d bytes for a block size of %d.\n"
  3300.              "\tTry selecting a small block size (with flag -s).\n",
  3301.              progName, draw, blockSize );
  3302.    showFileNames();
  3303.    cleanUpAndFail(1);
  3304. }
  3305.  
  3306.  
  3307. /*---------------------------------------------------*/
  3308. /*--- The main driver machinery                   ---*/
  3309. /*---------------------------------------------------*/
  3310.  
  3311. /*---------------------------------------------*/
  3312. void pad ( Char *s )
  3313. {
  3314.    Int32 i;
  3315.    if ( (Int32)strlen(s) >= longestFileName ) return;
  3316.    for (i = 1; i <= longestFileName - (Int32)strlen(s); i++)
  3317.       fprintf ( stderr, " " );
  3318. }
  3319.  
  3320.  
  3321. /*---------------------------------------------*/
  3322. Bool fileExists ( Char* name )
  3323. {
  3324. #ifdef BZ_RISCOS
  3325.    int regs[6];
  3326.    os_file( 17, name, regs );
  3327.    return regs[0] & 1;
  3328. #else
  3329.    FILE *tmp   = fopen ( name, "rb" );
  3330.    Bool exists = (tmp != NULL);
  3331.    if (tmp != NULL) fclose ( tmp );
  3332.    return exists;
  3333. #endif
  3334. }
  3335.  
  3336.  
  3337. /*---------------------------------------------*/
  3338. /*--
  3339.   if in doubt, return True
  3340. --*/
  3341. Bool notABogStandardFile ( Char* name )
  3342. {
  3343.    IntNative      i;
  3344.    struct MY_STAT statBuf;
  3345.  
  3346.    i = MY_LSTAT ( name, &statBuf );
  3347.    if (i != 0) return True;
  3348.    if (MY_S_IFREG(statBuf.st_mode)) return False;
  3349.    return True;
  3350. }
  3351.  
  3352.  
  3353. /*---------------------------------------------*/
  3354. void copyDateAndPermissions ( Char *srcName, Char *dstName )
  3355. {
  3356.    #if BZ_UNIX
  3357.    IntNative      retVal;
  3358.    struct MY_STAT statBuf;
  3359.    struct utimbuf uTimBuf;
  3360.  
  3361.    retVal = MY_LSTAT ( srcName, &statBuf );
  3362.    ERROR_IF_NOT_ZERO ( retVal );
  3363.    uTimBuf.actime = statBuf.st_atime;
  3364.    uTimBuf.modtime = statBuf.st_mtime;
  3365.  
  3366.    retVal = chmod ( dstName, statBuf.st_mode );
  3367.    ERROR_IF_NOT_ZERO ( retVal );
  3368.    retVal = utime ( dstName, &uTimBuf );
  3369.    ERROR_IF_NOT_ZERO ( retVal );
  3370.    #elif BZ_RISCOS
  3371.    int regs [6];
  3372.    os_file(17, srcName, regs);
  3373.    os_file(1, dstName, regs);
  3374.    #endif
  3375. }
  3376.  
  3377.  
  3378. /*---------------------------------------------*/
  3379. Bool endsInBz2 ( Char* name )
  3380. {
  3381. #ifdef BZ_RISCOS
  3382.    int regs[6];
  3383.    os_file(17, name, regs);
  3384.    return (((regs[2] & 0x000fff00) >> 8) == BZ_FILETYPE);
  3385. #else
  3386.    Int32 n = strlen ( name );
  3387.    if (n <= 4) return False;
  3388.    return
  3389.       (name[n-4] == '.' &&
  3390.        name[n-3] == 'b' &&
  3391.        name[n-2] == 'z' &&
  3392.        name[n-1] == '2');
  3393. #endif
  3394. }
  3395.  
  3396.  
  3397. /*---------------------------------------------*/
  3398. Bool containsDubiousChars ( Char* name )
  3399. {
  3400.    Bool cdc = False;
  3401.    for (; *name != '\0'; name++)
  3402.       if (*name == '?' || *name == '*') cdc = True;
  3403.    return cdc;
  3404. }
  3405.  
  3406.  
  3407. /*---------------------------------------------*/
  3408. void compress ( Char *name )
  3409. {
  3410.    FILE *inStr;
  3411.    FILE *outStr;
  3412.  
  3413.    if (name == NULL && srcMode != SM_I2O)
  3414.       panic ( "compress: bad modes\n" );
  3415.  
  3416.    switch (srcMode) {
  3417.       case SM_I2O: strcpy ( inName, "(stdin)" );
  3418.                    strcpy ( outName, "(stdout)" );
  3419.                    break;
  3420.       case SM_F2F: strcpy ( inName, name );
  3421. #ifdef BZ_RISCOS
  3422.            tmpnam ( outName );
  3423. #else
  3424.                    strcpy ( outName, name );
  3425.                    strcat ( outName, ".bz2" );
  3426. #endif
  3427.            break;
  3428.       case SM_F2O: strcpy ( inName, name );
  3429.                    strcpy ( outName, "(stdout)" );
  3430.                    break;
  3431.    }
  3432.  
  3433.    if ( srcMode != SM_I2O && containsDubiousChars ( inName ) ) {
  3434.       fprintf ( stderr, "%s: There are no files matching `%s'.\n",
  3435.       progName, inName );
  3436.       return;
  3437.    }
  3438.    if ( srcMode != SM_I2O && !fileExists ( inName ) ) {
  3439.       fprintf ( stderr, "%s: Input file %s doesn't exist, skipping.\n",
  3440.                 progName, inName );
  3441.       return;
  3442.    }
  3443.    if ( srcMode != SM_I2O && endsInBz2 ( inName )) {
  3444.       fprintf ( stderr, "%s: Input file name %s ends in `.bz2', skipping.\n",
  3445.                 progName, inName );
  3446.       return;
  3447.    }
  3448. #ifndef BZ_RISCOS
  3449.    if ( srcMode != SM_I2O && notABogStandardFile ( inName )) {
  3450.       fprintf ( stderr, "%s: Input file %s is not a normal file, skipping.\n",
  3451.                 progName, inName );
  3452.       return;
  3453.    }
  3454. #endif
  3455.    if ( srcMode == SM_F2F && fileExists ( outName ) ) {
  3456.       fprintf ( stderr, "%s: Output file %s already exists, skipping.\n",
  3457.                 progName, outName );
  3458.       return;
  3459.    }
  3460.  
  3461.    switch ( srcMode ) {
  3462.  
  3463.       case SM_I2O:
  3464.          inStr = stdin;
  3465.          outStr = stdout;
  3466.          if ( isatty ( fileno ( stdout ) ) ) {
  3467.             fprintf ( stderr,
  3468.                       "%s: I won't write compressed data to a terminal.\n",
  3469.                       progName );
  3470.             fprintf ( stderr, "%s: For help, type: `%s --help'.\n",
  3471.                               progName, progName );
  3472.             return;
  3473.          };
  3474.          break;
  3475.  
  3476.       case SM_F2O:
  3477.          inStr = fopen ( inName, "rb" );
  3478.          outStr = stdout;
  3479.          if ( isatty ( fileno ( stdout ) ) ) {
  3480.             fprintf ( stderr,
  3481.                       "%s: I won't write compressed data to a terminal.\n",
  3482.                       progName );
  3483.             fprintf ( stderr, "%s: For help, type: `%s --help'.\n",
  3484.                               progName, progName );
  3485.             return;
  3486.          };
  3487.          if ( inStr == NULL ) {
  3488.             fprintf ( stderr, "%s: Can't open input file %s, skipping.\n",
  3489.                       progName, inName );
  3490.             return;
  3491.          };
  3492.          break;
  3493.  
  3494.       case SM_F2F:
  3495.          inStr = fopen ( inName, "rb" );
  3496.          outStr = fopen ( outName, "wb" );
  3497.          if ( outStr == NULL) {
  3498.             fprintf ( stderr, "%s: Can't create output file %s, skipping.\n",
  3499.                       progName, outName );
  3500.             return;
  3501.          }
  3502.          if ( inStr == NULL ) {
  3503.             fprintf ( stderr, "%s: Can't open input file %s, skipping.\n",
  3504.                       progName, inName );
  3505.             return;
  3506.          };
  3507.          break;
  3508.  
  3509.       default:
  3510.          panic ( "compress: bad srcMode" );
  3511.          break;
  3512.    }
  3513.  
  3514.    if (verbosity >= 1) {
  3515.       fprintf ( stderr,  "  %s: ", inName );
  3516.       pad ( inName );
  3517.       fflush ( stderr );
  3518.    }
  3519.  
  3520.    /*--- Now the input and output handles are sane.  Do the Biz. ---*/
  3521.    outputHandleJustInCase = outStr;
  3522.    compressStream ( inStr, outStr );
  3523.    outputHandleJustInCase = NULL;
  3524.  
  3525.    /*--- If there was an I/O error, we won't get here. ---*/
  3526.    if ( srcMode == SM_F2F ) {
  3527.       copyDateAndPermissions ( inName, outName );
  3528.       if ( !keepInputFiles ) {
  3529.          IntNative retVal = remove ( inName );
  3530.          ERROR_IF_NOT_ZERO ( retVal );
  3531.       }
  3532. #ifdef BZ_RISCOS
  3533.       {
  3534.          int regs[3];
  3535.      rename( outName, inName );
  3536.      regs[2] = BZ_FILETYPE;
  3537.      os_file( 18, inName, regs);
  3538.       }
  3539. #endif
  3540.    }
  3541. }
  3542.  
  3543.  
  3544. /*---------------------------------------------*/
  3545. void uncompress ( Char *name )
  3546. {
  3547.    FILE *inStr;
  3548.    FILE *outStr;
  3549.    Bool magicNumberOK;
  3550.  
  3551.    if (name == NULL && srcMode != SM_I2O)
  3552.       panic ( "uncompress: bad modes\n" );
  3553.  
  3554.    switch (srcMode) {
  3555.       case SM_I2O: strcpy ( inName, "(stdin)" );
  3556.                    strcpy ( outName, "(stdout)" );
  3557.                    break;
  3558.       case SM_F2F: strcpy ( inName, name );
  3559. #ifdef BZ_RISCOS
  3560.            tmpnam( outName );
  3561. #else
  3562.                    strcpy ( outName, name );
  3563.                    if (endsInBz2 ( outName ))
  3564.                       outName [ strlen ( outName ) - 4 ] = '\0';
  3565. #endif
  3566.                    break;
  3567.       case SM_F2O: strcpy ( inName, name );
  3568.                    strcpy ( outName, "(stdout)" );
  3569.                    break;
  3570.    }
  3571.  
  3572.    if ( srcMode != SM_I2O && containsDubiousChars ( inName ) ) {
  3573.       fprintf ( stderr, "%s: There are no files matching `%s'.\n",
  3574.                 progName, inName );
  3575.       return;
  3576.    }
  3577.    if ( srcMode != SM_I2O && !fileExists ( inName ) ) {
  3578.       fprintf ( stderr, "%s: Input file %s doesn't exist, skipping.\n",
  3579.                 progName, inName );
  3580.       return;
  3581.    }
  3582.    if ( srcMode != SM_I2O && !endsInBz2 ( inName )) {
  3583.       fprintf ( stderr,
  3584.                 "%s: Input file name %s doesn't end in `.bz2', skipping.\n",
  3585.                 progName, inName );
  3586.       return;
  3587.    }
  3588. #ifndef BZ_RISCOS
  3589.    if ( srcMode != SM_I2O && notABogStandardFile ( inName )) {
  3590.       fprintf ( stderr, "%s: Input file %s is not a normal file, skipping.\n",
  3591.                 progName, inName );
  3592.       return;
  3593.    }
  3594. #endif
  3595.    if ( srcMode == SM_F2F && fileExists ( outName ) ) {
  3596.       fprintf ( stderr, "%s: Output file %s already exists, skipping.\n",
  3597.                 progName, outName );
  3598.       return;
  3599.    }
  3600.  
  3601.    switch ( srcMode ) {
  3602.  
  3603.       case SM_I2O:
  3604.          inStr = stdin;
  3605.          outStr = stdout;
  3606.          if ( isatty ( fileno ( stdin ) ) ) {
  3607.             fprintf ( stderr,
  3608.                       "%s: I won't read compressed data from a terminal.\n",
  3609.                       progName );
  3610.             fprintf ( stderr, "%s: For help, type: `%s --help'.\n",
  3611.                               progName, progName );
  3612.             return;
  3613.          };
  3614.          break;
  3615.  
  3616.       case SM_F2O:
  3617.          inStr = fopen ( inName, "rb" );
  3618.          outStr = stdout;
  3619.          if ( inStr == NULL ) {
  3620.             fprintf ( stderr, "%s: Can't open input file %s, skipping.\n",
  3621.                       progName, inName );
  3622.             return;
  3623.          };
  3624.          break;
  3625.  
  3626.       case SM_F2F:
  3627.          inStr = fopen ( inName, "rb" );
  3628.          outStr = fopen ( outName, "wb" );
  3629.          if ( outStr == NULL) {
  3630.             fprintf ( stderr, "%s: Can't create output file %s, skipping.\n",
  3631.                       progName, outName );
  3632.             return;
  3633.          }
  3634.          if ( inStr == NULL ) {
  3635.             fprintf ( stderr, "%s: Can't open input file %s, skipping.\n",
  3636.                       progName, inName );
  3637.             return;
  3638.          };
  3639.          break;
  3640.  
  3641.       default:
  3642.          panic ( "uncompress: bad srcMode" );
  3643.          break;
  3644.    }
  3645.  
  3646.    if (verbosity >= 1) {
  3647.       fprintf ( stderr, "  %s: ", inName );
  3648.       pad ( inName );
  3649.       fflush ( stderr );
  3650.    }
  3651.  
  3652.    /*--- Now the input and output handles are sane.  Do the Biz. ---*/
  3653.    outputHandleJustInCase = outStr;
  3654.    magicNumberOK = uncompressStream ( inStr, outStr );
  3655.    outputHandleJustInCase = NULL;
  3656.  
  3657.    /*--- If there was an I/O error, we won't get here. ---*/
  3658.    if ( magicNumberOK ) {
  3659.       if ( srcMode == SM_F2F ) {
  3660.          copyDateAndPermissions ( inName, outName );
  3661.          if ( !keepInputFiles ) {
  3662.             IntNative retVal = remove ( inName );
  3663.             ERROR_IF_NOT_ZERO ( retVal );
  3664.          }
  3665. #ifdef BZ_RISCOS
  3666.      {
  3667.         int regs[3];
  3668.         rename( outName, inName );
  3669.         regs[2] = 0xffd;
  3670.         os_file( 18, inName, regs );
  3671.      }
  3672. #endif
  3673.       }
  3674.    } else {
  3675.       if ( srcMode == SM_F2F ) {
  3676.          IntNative retVal = remove ( outName );
  3677.          ERROR_IF_NOT_ZERO ( retVal );
  3678.       }
  3679.    }
  3680.  
  3681.    if ( magicNumberOK ) {
  3682.       if (verbosity >= 1)
  3683.          fprintf ( stderr, "done\n" );
  3684.    } else {
  3685.       if (verbosity >= 1)
  3686.          fprintf ( stderr, "not a bzip2 file, skipping.\n" ); else
  3687.          fprintf ( stderr,
  3688.                    "%s: %s is not a bzip2 file, skipping.\n",
  3689.                    progName, inName );
  3690.    }
  3691.  
  3692. }
  3693.  
  3694.  
  3695. /*---------------------------------------------*/
  3696. void testf ( Char *name )
  3697. {
  3698.    FILE *inStr;
  3699.    Bool allOK;
  3700.  
  3701.    if (name == NULL && srcMode != SM_I2O)
  3702.       panic ( "testf: bad modes\n" );
  3703.  
  3704.    strcpy ( outName, "(none)" );
  3705.    switch (srcMode) {
  3706.       case SM_I2O: strcpy ( inName, "(stdin)" ); break;
  3707.       case SM_F2F: strcpy ( inName, name ); break;
  3708.       case SM_F2O: strcpy ( inName, name ); break;
  3709.    }
  3710.  
  3711.    if ( srcMode != SM_I2O && containsDubiousChars ( inName ) ) {
  3712.       fprintf ( stderr, "%s: There are no files matching `%s'.\n",
  3713.                 progName, inName );
  3714.       return;
  3715.    }
  3716.    if ( srcMode != SM_I2O && !fileExists ( inName ) ) {
  3717.       fprintf ( stderr, "%s: Input file %s doesn't exist, skipping.\n",
  3718.                 progName, inName );
  3719.       return;
  3720.    }
  3721.    if ( srcMode != SM_I2O && !endsInBz2 ( inName )) {
  3722.       fprintf ( stderr,
  3723.                 "%s: Input file name %s doesn't end in `.bz2', skipping.\n",
  3724.                 progName, inName );
  3725.       return;
  3726.    }
  3727. #ifndef BZ_RISCOS
  3728.    if ( srcMode != SM_I2O && notABogStandardFile ( inName )) {
  3729.       fprintf ( stderr, "%s: Input file %s is not a normal file, skipping.\n",
  3730.                 progName, inName );
  3731.       return;
  3732.    }
  3733. #endif
  3734.  
  3735.    switch ( srcMode ) {
  3736.  
  3737.       case SM_I2O:
  3738.          if ( isatty ( fileno ( stdin ) ) ) {
  3739.             fprintf ( stderr,
  3740.                       "%s: I won't read compressed data from a terminal.\n",
  3741.                       progName );
  3742.             fprintf ( stderr, "%s: For help, type: `%s --help'.\n",
  3743.                               progName, progName );
  3744.             return;
  3745.          };
  3746.          inStr = stdin;
  3747.          break;
  3748.  
  3749.       case SM_F2O: case SM_F2F:
  3750.          inStr = fopen ( inName, "rb" );
  3751.          if ( inStr == NULL ) {
  3752.             fprintf ( stderr, "%s: Can't open input file %s, skipping.\n",
  3753.                       progName, inName );
  3754.             return;
  3755.          };
  3756.          break;
  3757.  
  3758.       default:
  3759.          panic ( "testf: bad srcMode" );
  3760.          break;
  3761.    }
  3762.  
  3763.    if (verbosity >= 1) {
  3764.       fprintf ( stderr, "  %s: ", inName );
  3765.       pad ( inName );
  3766.       fflush ( stderr );
  3767.    }
  3768.  
  3769.    /*--- Now the input handle is sane.  Do the Biz. ---*/
  3770.    allOK = testStream ( inStr );
  3771.  
  3772.    if (allOK && verbosity >= 1) fprintf ( stderr, "ok\n" );
  3773.    if (!allOK) testFailsExist = True;
  3774. }
  3775.  
  3776.  
  3777. /*---------------------------------------------*/
  3778. void license ( void )
  3779. {
  3780.    fprintf ( stderr,
  3781.  
  3782.     "bzip2, a block-sorting file compressor.  "
  3783.     "Version 0.1pl2, 29-Aug-97.\n"
  3784.     "   \n"
  3785.     "   Copyright (C) 1996, 1997 by Julian Seward.\n"
  3786.     "   \n"
  3787.     "   This program is free software; you can redistribute it and/or modify\n"
  3788.     "   it under the terms of the GNU General Public License as published by\n"
  3789.     "   the Free Software Foundation; either version 2 of the License, or\n"
  3790.     "   (at your option) any later version.\n"
  3791.     "   \n"
  3792.     "   This program is distributed in the hope that it will be useful,\n"
  3793.     "   but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
  3794.     "   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n"
  3795.     "   GNU General Public License for more details.\n"
  3796.     "   \n"
  3797.     "   You should have received a copy of the GNU General Public License\n"
  3798.     "   along with this program; if not, write to the Free Software\n"
  3799.     "   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n"
  3800.     "   \n"
  3801.     "   The GNU General Public License is contained in the file LICENSE.\n"
  3802.     "   \n"
  3803.    );
  3804. }
  3805.  
  3806.  
  3807. /*---------------------------------------------*/
  3808. void usage ( Char *fullProgName )
  3809. {
  3810.    fprintf (
  3811.       stderr,
  3812.       "bzip2, a block-sorting file compressor.  "
  3813.       "Version 0.1pl2, 29-Aug-97.\n"
  3814.       "\n   usage: %s [flags and input files in any order]\n"
  3815.       "\n"
  3816.       "   -h --help           print this message\n"
  3817.       "   -d --decompress     force decompression\n"
  3818.       "   -f --compress       force compression\n"
  3819.       "   -t --test           test compressed file integrity\n"
  3820.       "   -c --stdout         output to standard out\n"
  3821.       "   -v --verbose        be verbose (a 2nd -v gives more)\n"
  3822.       "   -k --keep           keep (don't delete) input files\n"
  3823.       "   -L --license        display software version & license\n"
  3824.       "   -V --version        display software version & license\n"
  3825.       "   -s --small          use less memory (at most 2500k)\n"
  3826.       "   -1 .. -9            set block size to 100k .. 900k\n"
  3827.       "   --repetitive-fast   compress repetitive blocks faster\n"
  3828.       "   --repetitive-best   compress repetitive blocks better\n"
  3829.       "\n"
  3830.       "   If invoked as `bzip2', the default action is to compress.\n"
  3831.       "              as `bunzip2', the default action is to decompress.\n"
  3832.       "\n"
  3833.       "   If no file names are given, bzip2 compresses or decompresses\n"
  3834.       "   from standard input to standard output.  You can combine\n"
  3835.       "   flags, so `-v -4' means the same as -v4 or -4v, &c.\n"
  3836.       #if BZ_UNIX
  3837.       "\n"
  3838.       #endif
  3839.       ,
  3840.  
  3841.       fullProgName
  3842.    );
  3843. }
  3844.  
  3845.  
  3846. /*---------------------------------------------*/
  3847. /*--
  3848.   All the garbage from here to main() is purely to
  3849.   implement a linked list of command-line arguments,
  3850.   into which main() copies argv[1 .. argc-1].
  3851.  
  3852.   The purpose of this ridiculous exercise is to
  3853.   facilitate the expansion of wildcard characters
  3854.   * and ? in filenames for halfwitted OSs like
  3855.   MSDOS, Windows 95 and NT.
  3856.  
  3857.   The actual Dirty Work is done by the platform-specific
  3858.   macro APPEND_FILESPEC.
  3859. --*/
  3860.  
  3861. typedef
  3862.    struct zzzz {
  3863.       Char        *name;
  3864.       struct zzzz *link;
  3865.    }
  3866.    Cell;
  3867.  
  3868.  
  3869. /*---------------------------------------------*/
  3870. void *myMalloc ( Int32 n )
  3871. {
  3872.    void* p;
  3873.  
  3874.    p = malloc ( (size_t)n );
  3875.    if (p == NULL) {
  3876.       fprintf (
  3877.          stderr,
  3878.          "%s: `malloc' failed on request for %d bytes.\n",
  3879.          progName, n
  3880.       );
  3881.       exit ( 1 );
  3882.    }
  3883.    return p;
  3884. }
  3885.  
  3886.  
  3887. /*---------------------------------------------*/
  3888. Cell *mkCell ( void )
  3889. {
  3890.    Cell *c;
  3891.  
  3892.    c = (Cell*) myMalloc ( sizeof ( Cell ) );
  3893.    c->name = NULL;
  3894.    c->link = NULL;
  3895.    return c;
  3896. }
  3897.  
  3898.  
  3899. /*---------------------------------------------*/
  3900. Cell *snocString ( Cell *root, Char *name )
  3901. {
  3902.    if (root == NULL) {
  3903.       Cell *tmp = mkCell();
  3904.       tmp->name = (Char*) myMalloc ( 5 + strlen(name) );
  3905.       strcpy ( tmp->name, name );
  3906.       return tmp;
  3907.    } else {
  3908.       Cell *tmp = root;
  3909.       while (tmp->link != NULL) tmp = tmp->link;
  3910.       tmp->link = snocString ( tmp->link, name );
  3911.       return root;
  3912.    }
  3913. }
  3914.  
  3915.  
  3916.  
  3917. /*---------------------------------------------*/
  3918. #define ISFLAG(s) (strcmp(aa->name, (s))==0)
  3919.  
  3920.  
  3921. IntNative main ( IntNative argc, Char *argv[] )
  3922. {
  3923.    Int32  i, j;
  3924.    Char   *tmp;
  3925.    Cell   *argList;
  3926.    Cell   *aa;
  3927.  
  3928.  
  3929.    #if DEBUG
  3930.       fprintf ( stderr, "bzip2: *** compiled with debugging ON ***\n" );
  3931.    #endif
  3932.  
  3933.    /*-- Be really really really paranoid :-) --*/
  3934.    if (sizeof(Int32) != 4 || sizeof(UInt32) != 4  ||
  3935.        sizeof(Int16) != 2 || sizeof(UInt16) != 2  ||
  3936.        sizeof(Char)  != 1 || sizeof(UChar)  != 1) {
  3937.       fprintf ( stderr,
  3938.                 "bzip2: I'm not configured correctly for this platform!\n"
  3939.                 "\tI require Int32, Int16 and Char to have sizes\n"
  3940.                 "\tof 4, 2 and 1 bytes to run properly, and they don't.\n"
  3941.                 "\tProbably you can fix this by defining them correctly,\n"
  3942.                 "\tand recompiling.  Bye!\n" );
  3943.       exit(1);
  3944.    }
  3945.  
  3946.  
  3947.    /*-- Set up signal handlers --*/
  3948.    signal (SIGINT,  mySignalCatcher);
  3949.    signal (SIGTERM, mySignalCatcher);
  3950.    signal (SIGSEGV, mySIGSEGVorSIGBUScatcher);
  3951.    #if BZ_UNIX
  3952.    signal (SIGHUP,  mySignalCatcher);
  3953.    signal (SIGBUS,  mySIGSEGVorSIGBUScatcher);
  3954.    #endif
  3955.  
  3956.  
  3957.    /*-- Initialise --*/
  3958.    outputHandleJustInCase  = NULL;
  3959.    ftab                    = NULL;
  3960.    ll4                     = NULL;
  3961.    ll16                    = NULL;
  3962.    ll8                     = NULL;
  3963.    tt                      = NULL;
  3964.    block                   = NULL;
  3965.    zptr                    = NULL;
  3966.    smallMode               = False;
  3967.    keepInputFiles          = False;
  3968.    verbosity               = 0;
  3969.    blockSize100k           = 9;
  3970.    testFailsExist          = False;
  3971.    bsStream                = NULL;
  3972.    numFileNames            = 0;
  3973.    numFilesProcessed       = 0;
  3974.    workFactor              = 30;
  3975.  
  3976.    strcpy ( inName,  "(none)" );
  3977.    strcpy ( outName, "(none)" );
  3978.  
  3979.    strcpy ( progNameReally, argv[0] );
  3980.    progName = &progNameReally[0];
  3981.    for (tmp = &progNameReally[0]; *tmp != '\0'; tmp++)
  3982.       if (*tmp == PATH_SEP) progName = tmp + 1;
  3983.  
  3984.  
  3985.    /*-- Expand filename wildcards in arg list --*/
  3986.    argList = NULL;
  3987.    for (i = 1; i <= argc-1; i++)
  3988.       APPEND_FILESPEC(argList, argv[i]);
  3989.  
  3990.  
  3991.    /*-- Find the length of the longest filename --*/
  3992.    longestFileName = 7;
  3993.    numFileNames    = 0;
  3994.    for (aa = argList; aa != NULL; aa = aa->link)
  3995.       if (aa->name[0] != '-') {
  3996.          numFileNames++;
  3997.          if (longestFileName < (Int32)strlen(aa->name) )
  3998.             longestFileName = (Int32)strlen(aa->name);
  3999.       }
  4000.  
  4001.  
  4002.    /*-- Determine what to do (compress/uncompress/test). --*/
  4003.    /*-- Note that subsequent flag handling may change this. --*/
  4004.    opMode = OM_Z;
  4005.  
  4006.    if ( (strcmp ( "bunzip2",     progName ) == 0) ||
  4007.         (strcmp ( "BUNZIP2",     progName ) == 0) ||
  4008.         (strcmp ( "bunzip2.exe", progName ) == 0) ||
  4009.         (strcmp ( "BUNZIP2.EXE", progName ) == 0) )
  4010.       opMode = OM_UNZ;
  4011.  
  4012.  
  4013.    /*-- Determine source modes; flag handling may change this too. --*/
  4014.    if (numFileNames == 0)
  4015.       srcMode = SM_I2O; else srcMode = SM_F2F;
  4016.  
  4017.  
  4018.    /*-- Look at the flags. --*/
  4019.    for (aa = argList; aa != NULL; aa = aa->link)
  4020.       if (aa->name[0] == '-' && aa->name[1] != '-')
  4021.          for (j = 1; aa->name[j] != '\0'; j++)
  4022.             switch (aa->name[j]) {
  4023.                case 'c': srcMode          = SM_F2O; break;
  4024.                case 'd': opMode           = OM_UNZ; break;
  4025.                case 'f': opMode           = OM_Z; break;
  4026.                case 't': opMode           = OM_TEST; break;
  4027.                case 'k': keepInputFiles   = True; break;
  4028.                case 's': smallMode        = True; break;
  4029.                case '1': blockSize100k    = 1; break;
  4030.                case '2': blockSize100k    = 2; break;
  4031.                case '3': blockSize100k    = 3; break;
  4032.                case '4': blockSize100k    = 4; break;
  4033.                case '5': blockSize100k    = 5; break;
  4034.                case '6': blockSize100k    = 6; break;
  4035.                case '7': blockSize100k    = 7; break;
  4036.                case '8': blockSize100k    = 8; break;
  4037.                case '9': blockSize100k    = 9; break;
  4038.                case 'V':
  4039.                case 'L': license();            break;
  4040.                case 'v': verbosity++; break;
  4041.                case 'h': usage ( progName );
  4042.                          exit ( 1 );
  4043.                          break;
  4044.                default:  fprintf ( stderr, "%s: Bad flag `%s'\n",
  4045.                                    progName, aa->name );
  4046.                          usage ( progName );
  4047.                          exit ( 1 );
  4048.                          break;
  4049.          }
  4050.  
  4051.    /*-- And again ... --*/
  4052.    for (aa = argList; aa != NULL; aa = aa->link) {
  4053.       if (ISFLAG("--stdout"))            srcMode          = SM_F2O;  else
  4054.       if (ISFLAG("--decompress"))        opMode           = OM_UNZ;  else
  4055.       if (ISFLAG("--compress"))          opMode           = OM_Z;    else
  4056.       if (ISFLAG("--test"))              opMode           = OM_TEST; else
  4057.       if (ISFLAG("--keep"))              keepInputFiles   = True;    else
  4058.       if (ISFLAG("--small"))             smallMode        = True;    else
  4059.       if (ISFLAG("--version"))           license();                  else
  4060.       if (ISFLAG("--license"))           license();                  else
  4061.       if (ISFLAG("--repetitive-fast"))   workFactor = 5;             else
  4062.       if (ISFLAG("--repetitive-best"))   workFactor = 150;           else
  4063.       if (ISFLAG("--verbose"))           verbosity++;                else
  4064.       if (ISFLAG("--help"))              { usage ( progName ); exit ( 1 ); }
  4065.          else
  4066.          if (strncmp ( aa->name, "--", 2) == 0) {
  4067.             fprintf ( stderr, "%s: Bad flag `%s'\n", progName, aa->name );
  4068.             usage ( progName );
  4069.             exit ( 1 );
  4070.          }
  4071.    }
  4072.  
  4073.    if (opMode == OM_Z && smallMode) blockSize100k = 2;
  4074.  
  4075.    if (opMode == OM_Z && srcMode == SM_F2O && numFileNames > 1) {
  4076.       fprintf ( stderr, "%s: I won't compress multiple files to stdout.\n",
  4077.                 progName );
  4078.       exit ( 1 );
  4079.    }
  4080.  
  4081.    if (srcMode == SM_F2O && numFileNames == 0) {
  4082.       fprintf ( stderr, "%s: -c expects at least one filename.\n",
  4083.                 progName );
  4084.       exit ( 1 );
  4085.    }
  4086.  
  4087.    if (opMode == OM_TEST && srcMode == SM_F2O) {
  4088.       fprintf ( stderr, "%s: -c and -t cannot be used together.\n",
  4089.                 progName );
  4090.       exit ( 1 );
  4091.    }
  4092.  
  4093.    if (opMode != OM_Z) blockSize100k = 0;
  4094.  
  4095.    if (opMode == OM_Z) {
  4096.       allocateCompressStructures();
  4097.       if (srcMode == SM_I2O)
  4098.          compress ( NULL );
  4099.          else
  4100.          for (aa = argList; aa != NULL; aa = aa->link)
  4101.             if (aa->name[0] != '-') {
  4102.                numFilesProcessed++;
  4103.                compress ( aa->name );
  4104.             }
  4105.    } else
  4106.    if (opMode == OM_UNZ) {
  4107.       if (srcMode == SM_I2O)
  4108.          uncompress ( NULL );
  4109.          else
  4110.          for (aa = argList; aa != NULL; aa = aa->link)
  4111.             if (aa->name[0] != '-') {
  4112.                numFilesProcessed++;
  4113.                uncompress ( aa->name );
  4114.             }
  4115.    } else {
  4116.       testFailsExist = False;
  4117.       if (srcMode == SM_I2O)
  4118.          testf ( NULL );
  4119.          else
  4120.          for (aa = argList; aa != NULL; aa = aa->link)
  4121.             if (aa->name[0] != '-') {
  4122.                numFilesProcessed++;
  4123.                testf ( aa->name );
  4124.             }
  4125.       if (testFailsExist) {
  4126.          fprintf ( stderr,
  4127.            "\n"
  4128.            "You can use the `bzip2recover' program to *attempt* to recover\n"
  4129.            "data from undamaged sections of corrupted files.\n\n"
  4130.          );
  4131.          exit(2);
  4132.       }
  4133.    }
  4134.    return 0;
  4135. }
  4136.  
  4137.  
  4138. /*-----------------------------------------------------------*/
  4139. /*--- end                                         bzip2.c ---*/
  4140. /*-----------------------------------------------------------*/
  4141.